Home > Back-end >  Why am I getting undefined when trying to update state
Why am I getting undefined when trying to update state

Time:07-31

Basically I am getting coords from a library and updating the state's latitude and longitude to hold them however I get undefined, what may be the reason?

This is my code

const [latitude , setLatitiude] = useState(null)
 const [longitude , setLongitude] = useState(null)
    
const {coords, isGeolocationAvailable , isGeolocationEnabled} = useGeolocated({
        positionOptions: {
            enableHighAccuracy: false
        },
        userDecisionTimeout: 5000
    })


    useEffect (() => {
        setLatitiude(coords.latitude)
        setLongitude(coords.longitude)
    }, [longitude , latitude])

Any idea why I am getting that error of undefined, when surely there is data in the coords variable. I know there is data in coords because I console.logged it.

CodePudding user response:

You should be defining the right dependency on useEffect

useEffect (() => {
    console.log(coords);
    if (coords) {
       setLatitiude(coords.latitude)
       setLongitude(coords.longitude) 
    }
}, [coords]);

Now if you wanted to see the updated latitude and longitude state value then write another useEffect with required dependency as setState is asynchronous.

useEffect (() => {
   console.log(`latitude: ${latitude}; longitude: ${longitude}`);
}, [latitude, longitude]);
  • Related