Search code examples
reactjsnext.jsleafletreact-leaflet

Can't set lat, lng in state


I get the lat and lng when the user clicks on the map, and I console.log them. This works fine, but after when I would like to set them in a state I get this error: enter image description here

I don't know how could this occur, since both were defined, and worked just two lines ago.

The necessary code:

const [userPickPos, setUserPickPos] = useState()
  const MapEvents = () => {
    useMapEvents({
      click(e) {
        const lat = e.latlng.lat;
        console.log(lat) //works fine
        const lng = e.latlng.lng;
        console.log(lng) //works fine

        setUserPickPos(lat, lng) //gives me the error

      },
    });
}

Solution

  • you should pass the whole object to useState defined setter:

    setUserPickPos({lat: lat, lng: lng})