简体   繁体   中英

Reactjs How would I display a simple error if no data is fetched from api?

I'm struggling to find a way of adding an error message is filteredCountries from an api === 0. How would I best do this is a simple manner? Or is there a simple way to route to a 404 page?

I can think along the correct lines it's just not clicking!

const CountryList = ({ filteredCountries, isLoading }) => {
  return (
    <div className='card-list'>
      {isLoading ? (
        <Loader isLoading={isLoading} />
      ) : (
        filteredCountries.map((country) => (
          <>
            <Country
              key={country.name}
              id={country.alpha3Code}
              country={country}
            />
          </>
        ))
      )}
    </div>
  );
};
export default CountryList;

You could form another conditional and check by the filteredCountries' length . It technically wouldn't be considered an error per se but from what I understand this is what you wanted:

const CountryList = ({ filteredCountries, isLoading }) => {
  return (
    <div className='card-list'>
      {isLoading ? (
        <Loader isLoading={isLoading} />
      ) : (
        filteredCountries.length ? (
          'No countries found'
        ) : (
          filteredCountries.map((country) => (
            <>
              <Country
                key={country.name}
                id={country.alpha3Code}
                country={country}
              />
            </>
        )))
      )}
    </div>
  );
};
export default CountryList;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM