Search code examples
reactjsgeolocationreact-hooksuse-effectuse-state

Can't store navigator.geolocation data in useffect, with a usestate


I have a problem, I want to store latitude and longitude from navigator.geolocation in a useEffect before the render, with an empty array but when I console.log my result it displays null.

Here is the part concerned.

import React, {useState, useEffect} from 'react';

const [userPos, setUserPos] = useState({lat: null, long: null})

 useEffect(() => {
      navigator.geolocation.getcurrentposition((pos) =>{
          console.log(pos.coords.latitude + " " + pos.coords.longitude) // display VALUE
          setUserPos({ 
                lat: pos.coords.latitude,
                long: pos.coords.longitude,
           }) // store data in usestate
          console.log(userPos) // Display Null
     }, (err) => {
          console.log(err);
     },options);
    }
  })
 }, [])

So why, when I log pos.coords in the useEffect I have the value but not when I log my state. Any ideas?


Solution

  • React can't re-render your function half way through. Instead create a new variable that you pass to your set function and use it after. Do note that userPos will be available to you outside the useEffect after re-render. So the new variable is only useful to you within the same useEffect function.

    import React, {useState, useEffect} from 'react';
    
    const [userPos, setUserPos] = useState({lat: null, long: null})
    
     useEffect(() => {
          navigator.geolocation.getcurrentposition((pos) =>{
              console.log(pos.coords.latitude + " " + pos.coords.longitude) // display VALUE
              const newUserPos = { 
                    lat: pos.coords.latitude,
                    long: pos.coords.longitude,
               };
              setUserPos(newUserPos) // store data in usestate
              console.log(newUserPos) // Display your values
         }, (err) => {
              console.log(err);
         },options);
        }
      })
     }, [])