I am learning react hooks
. In my code I have set the initial values for plotting map as
//map state
const [mapData, setMapData] = useState(
{ lat: 40.712776, lng: -74.0059, zoom: 5 }
);
In the useEffect()
call back I am loading the map once
useEffect(() => {
initMap();
}, []); // run once
Inside the initMap()
there is map.on()
method to get the updated geo locations. The initMap()
is
const initMap = () => {
mapboxgl.accessToken = 'token';
const map = new mapboxgl.Map({
container: mapContainer,
style: 'mapbox://styles/mapbox/streets-v11',
center: [mapData.lng, mapData.lat],
zoom: mapData.zoom
}); // load the map with init values
// update the `mapData` as map move
map.on('moveend', () => {
const { lng, lat } = map.getCenter(); // logs the updated lat and lon
setMapData({ lat: lat.toFixed(4), lng: lng.toFixed(4), zoom: map.getZoom().toFixed(2) }); // suppose to set the updated value
console.log(mapData); // not logging updated values!
});
}
The setMapData()
is not setting the state. But the map.on
is called and is logging the values.