Home > Software design >  Can't set the location to the state
Can't set the location to the state

Time:09-10

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

CodePudding user response:

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

CodePudding user response:

but let me guess, in the second time you click it log the current location.

setMyLocation() does not immediately mutate myLocation but creates a pending state transition. Accessing myLocation after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setMyLocation() and calls may be batched for performance gains.

you can think of your myLocation state as a "snapshot" of the state related to the current render. after mutate the state, the component will re-render with the new state you set.

in your example you are trying to use the state you changed the line before but it will update just after the next render.

In conclusion, the state indeed changing. you can check it this way:

function Geolocation() {
  const [myLocation, setMyLocation] = useState(null);

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

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

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