Home > database >  i want to add all countries to state but problem is state only returning one country
i want to add all countries to state but problem is state only returning one country

Time:10-03

Hi guys i want to add al countries to state but problem is state only returning one country

const [country, getCountry] = useState([]); useEffect(() => {
axios
  .request("https://restcountries.com/v3.1/all")
  .then((response) => {
    response.data.forEach((element) => {
      getCountry(element.name.official);
    });
  })
  .catch(function (error) {
    console.error(error);
  }); }, []);

CodePudding user response:

You are setting one by one and the last one will be final state so you may do as following:

 .then((response) => {
    getCountry(response.data.map((element) => element.name.official))
  })

CodePudding user response:

First, you need to store all the countries in another array, and then you can store that array in your state. What you are doing now is updating your state with a different country in each iteration. That's why you're getting a single country in your state. I've updated your implementation which worked for me, but instead to forEach you should look into map : Array.prototype.map()

const [country, setCountry] = useState([])
useEffect(() => {
    axios
    .request("https://restcountries.com/v3.1/all")
    .then((response) => {
        const countries = []
        response.data.forEach((element) => {
            countries.push(element.name.official);
        });
        setCountry(countries);
    })
    .catch(function (error) {
        console.error(error);
    }); 
}, []);
  • Related