-2

I'm using the google-map-react component and I'm attempting to set the coordinates of the position the user clicked on. I have the coordinates, however the first time I click on the map (and the click event is fired), the array coordinates returns an empty array.

This is resulting in weird behaviour, where each click returns the coordinates of the previous click? Can anyone see whats going on here?

const Map = ({ center, zoom}) => {

    const [ coordinates, setCoordinates ] = useState([]);

    const onMapClick = ({ lat, lng }) => {
        setCoordinates([lat, lng]);
        console.log(coordinates)
    };

    return (
        <div className="map">
            <GoogleMapReact 
                bootstrapURLKeys={{ key: 'redacted' }}
                defaultCenter={center}
                defaultZoom={zoom}
                onClick={onMapClick}
            />
        </div>
    );
};

Map.defaultProps = {
    center: {
        lat: 53.3439,
        lng: 33.0622
    },
    zoom: 5
}

The behaviour is logging the following

[]
(2) [51.13790387040561, -11.71807343750003]
(2) [47.709656855536565, 2.1686453124999705]

The second log, should be in position 1, and the third log should be in position 2.

  • 2
    Duplicate of [console log the state after using useState doesn't return the current value](https://stackoverflow.com/questions/54867616/console-log-the-state-after-using-usestate-doesnt-return-the-current-value) – MrUpsidown Dec 10 '20 at 11:59

1 Answers1

1

There is an async behavior on useState. Your console.log() will show the old one. Because the state is not updated yet. But if you put your console.log() in useEffect like

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

You will see it's showing properly after the onClick event.

Your code is working normally. You can put your coordinates state where you want to use them.

Akif
  • 7,098
  • 7
  • 27
  • 53
Mesut Uçar
  • 162
  • 1
  • 8