sooon
sooon

Reputation: 4878

react - useState never update the value

I have this function component:

export default function Proximity (props){
  // const [center, setCenter] = useState([3.1397, 101.6852]);
  const [lat, setLat] = useState(3.333);
  const [lng, setLng] = useState(2.222);


useEffect(()=>{
      getLocation()
    },[])

function getLocation(){
      navigator.geolocation.getCurrentPosition(function(pos) {

          console.log(pos.coords.latitude) // <-- 4.444
          console.log(pos.coords.longitude)// <-- 5.555

          setLat(pos.coords.latitude) ///<-- update lat value
          setLng(pos.coords.longitude) ///<-- update lng value

          console.log(lat) //<-- 3.333
          console.log(lng) //<-- 2.222
      });
    }

}
...
}

for some reasons, the setLat and setLng never update the value. getLocation is just one of the example. I have other functions also use setLat and setLng, when I get lat and lng, I always get back 3.333 and 2.222.

What seems to be the problem? How can I resolve this?

Upvotes: 0

Views: 47

Answers (1)

Giovanni Esposito
Giovanni Esposito

Reputation: 11156

setLat and setLng are async and you cannot log updated values just after setted. In this case you should use useEffect hook to log the latest values. Something like:

useEffect(() => {
  console.log(lat);
}, [lat]);

useEffect(() => {
  console.log(lng);
}, [lng]);

Upvotes: 3

Related Questions