0

I'm trying to fetch data from an API, and encountered an issue. The function fetchCountryData doesn't help debug the issue because any breakpoints inside it are ignored. How do I step into an async function?

const [countryData, setCountryData] = React.useState([]);
const [borderCountries, setBorderCountries] = React.useState([]);

React.useEffect(() => {
    fetchCountryData();
}, [])

async function fetchCountryData() {
    /* fetch country by Name */
    const response = await 
        fetch(`https://restcountries.eu/rest/v2/name/${match.params.country}
               ?fields=${URL_FIELD_QUERIES}`);

    const fetchedData = await response.json();
        
    /* check if query by name returned multiple countries (the api unwillingly does that for some countries!) */
    let index = fetchedData.length === 1
                    ?   0   :   filterRequiredCountry(fetchedData, match.params.country);

    setCountryData(fetchedData[index]);

        
    /* .map() will run 'fetchNeighborName' function for each borders' item */
    const promises = fetchedData[index].borders.map(fetchNeighborName);

    /* the above promises will be resolved by Promise.all() */
    const neighborNames = await Promise.all(promises);

    setBorderCountries(neighborNames);
}

/* Extract 'alphaCode' for each bordered country and fetch its real name */

async function fetchNeighborName(alphaCode) {
    return fetch(`https://restcountries.eu/rest/v2/alpha/${alphaCode}?fields=name`)
        .then(response => response.json())
        .then(data => data.name);
}

function filterRequiredCountry(fetchedData, requiredCountry) {
    let requiredIndex;

    for (let index = 0; index < fetchedData.length; index++) {

        if (fetchedData[index].name === requiredCountry.toLowerCase()) {
            requiredIndex = index; break;
        }
    }
}
Sapinder
  • 183
  • 10

0 Answers0