0

It's React. Something weird happens. When I reload directly from the browser, it still logs an empty array, but when I save the file from VSCode, it displays the array just like I wanted.

const [country, setCountry] = useState([]);
    
useEffect(() => {
  axios.get("https://restcountries.com/v3.1/all")
    .then((response) => {
      const data = response.data;
      const names = data.map((n) => n.name.common);
      setCountry(names);
      console.log(country);
    })
    .catch((error) => {
      console.log(error);
    });
}, []);
devpolo
  • 2,487
  • 3
  • 12
  • 28
Haki
  • 11
  • 5
  • 1
    that is because `setCountry` is `async` so when you are logging `country` at that time value is not yet changed. – DecPK Mar 04 '23 at 23:02
  • @DecPK I don't understand this. So you're saying that my log is executed before setCountry() ? – Haki Mar 04 '23 at 23:10
  • `setCountry` is not `async`. Have you tried: `setCountry(prev => […prev, …names])` – devpolo Mar 04 '23 at 23:19
  • @devpolo No buenos. Same thing still. – Haki Mar 04 '23 at 23:27
  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Konrad Mar 05 '23 at 20:04
  • `console.log(country)` will never show the new value of `country` if you use `setCountry` in the same function. If you want to know the new value of `country` either just move the `console log` to the component's body or use `useEffect` – Konrad Mar 05 '23 at 20:05

0 Answers0