arraysreactjsasync-awaitaxiosreact-lifecycle

Problem accessing data of an array created from the state in Reactjs


I have an array of country codes and I need to have the name. I am trying to access the countries data from the state (axios call) and from there filter by country code, and from that new array, extract the common name of the country. (I am using the restcountries.com api).

-If I create a new state to map from, I get the too many re-renders. -Right now, Although the border countries info is there, I can't access it, I get the "Cannot read properties of undefined" error, that usually is tied to a lifecycle issue, therefore I am using a condition on when to access the information. Still I am not able to get it stable and return the name that I need. Can someone please take a look and tell me what am I doing wrong? Thanks in advance

import axios from "axios";

const BorderCountries = (props) => {
  const [countriesList, setCountriesList] = useState([]);

  useEffect(() => {
    axios
      .get(`https://restcountries.com/v3.1/all`)
      .then((countries) => setCountriesList(countries.data))
      .catch((error) => console.log(`${error}`));
  }, []);

  const getCountryName = () => {
    const codes = props.data;

    const borderCountries = [];
    codes.map((code) => {
      const borderCountry = countriesList.filter((country) =>
        country.cca3.includes(code)
      );
      borderCountries.push(borderCountry);
    });
    // console.log(borderCountries);

    if (props.data.length === borderCountries.length) {
      const borderName = borderCountries.map((border) =>
        console.log(border[0].name.common)
      );
      return borderName
    }
  };

  return (
    <div>
      <h3>Border Countries:</h3>
      {getCountryName()}
    </div>
  );
};

export default BorderCountries;

Solution

  • const getCountryName = () => {
        const codes = props.data;
    
        if(countriesList.length === 0) return <></>;
    
        const borderCountries = [];
        codes.map((code) => {
          const borderCountry = countriesList.filter((country) =>
            country.cca3.includes(code)
          );
          borderCountries.push(borderCountry);
        });
        // console.log(borderCountries);
    
        if (props.data.length === borderCountries.length) {
          const borderName = borderCountries.map((border) =>
            console.log(border[0].name.common)
          );
          return borderName
        }
      };
    

    Try this, you forgot to wait for the call to finish.