Search code examples
reactjsgeolocationstate

Can't set the location to the state


I'm trying to set the location to the state, but the first time i click the button the state is null not the current location. Why?

function Geolocation() {

  const [myLocation, setMyLocation] = useState(null)

  const getLocation = () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(setMyLocation);
      console.log(myLocation)
    } else {
      alert("Geolocation is not supported by this browser.")
    }
  }

  return (
    <div>
      <button onClick={getLocation}>Get geolocation</button>
    </div>
  )
}

export default Geolocation

Solution

  • There is not a propblem. Just Console.log works faster than getLocation() function. You can see it in this code:

    function Geolocation() {
    
      const [myLocation, setMyLocation] = useState(null)
    
      const getLocation = () => {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(setMyLocation);
          console.log(myLocation)
        } else {
          alert("Geolocation is not supported by this browser.")
        }
      }
    
      return (
        <div>
          <button onClick={getLocation}>{myLocation?.timestamp || "null"}</button>
        </div>
      )
    }
    
    export default Geolocation