0

I am trying to change the state of my map. My code is quite simple. But i can't figure out why it's not working.

const [mapCenter, setMapCenter] = useState({ lat: 34.80746, lng: -40.4796 });

 const onCountryChange = async (e) => {
    const countryCode = e.target.value

    const url = countryCode === 'Worldwide' ? 'https://disease.sh/v3/covid-19/all' : `https://disease.sh/v3/covid-19/countries/${countryCode}`

    await fetch(url).then(response => response.json()).then((data) => {
      setCountry(countryCode);
      setCountryInfo(data);
      
      console.log(data.countryInfo.lat, data.countryInfo.lng)

      setMapCenter([data.countryInfo.lat, data.countryInfo.lng]);
      setMapZoom(6)
      console.log(mapCenter, mapZoom)
    })
  }

In my onCountryChange function, I am calling data from an API and setting the data in the UI, which is working fine, but the setMapCenter data fails to update. When I log the response I get from the API, I get the correct response in the console, but when I log the state of mapCenter, it still returns the initial state... what am I doing wrong please?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Kelly
  • 111
  • 1
  • 5
  • `useState` is asyncronous, use `useEffect` to access updated data – Nadia Chibrikova Jan 24 '21 at 10:29
  • Please can you show me an example? – Kelly Jan 24 '21 at 11:07
  • Your question has been closed as a duplicate, so I cannot answer it, have you tried reading the answers here https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately ? – Nadia Chibrikova Jan 24 '21 at 11:13
  • There's a lot of answers over here... I can't get my head around my main issue... – Kelly Jan 24 '21 at 11:18
  • 1
    Move all the logic that requires updated data into `useEffect` https://reactjs.org/docs/hooks-reference.html#useeffect – Nadia Chibrikova Jan 24 '21 at 11:24
  • If you simply want to log updated state: `useEffect(() => console.log(mapCenter, mapZoom), [mapCenter, mapZoom]);`. – Drew Reese Jan 24 '21 at 18:21
  • Thanks very much for the help guys... But it's not working perfectly yet. I already tried logging the updated state inside useEffect, and it's coming out fine in the console. But i have an issue with actually making the state update in my app. The state is truly being updated at the change of each country's mapCenter and mapZoom values... But no real change is happening in my app. – Kelly Jan 25 '21 at 08:00
  • useEffect(() => console.log(mapCenter, mapZoom), [mapCenter, mapZoom]); This is exctly what I have in my useEffect. But i don't know why the state is not changing in my app... since it's logging the correct value of the new state in the console, then there should be changes in my app right? – Kelly Jan 25 '21 at 08:01

0 Answers0