'React useState hook does not update the lonlat value in OSM
I´m stucked with not updating react useState hook setPosition(lonLat) line 34. Could someone advise me please why that does not working? The position const is still a 'test' string.
import 'ol/ol.css'
import Map from "ol/Map"
import OSM from "ol/source/OSM"
import Tile from "ol/layer/Tile"
import View from "ol/View"
import {fromLonLat, toLonLat} from 'ol/proj'
export const useMap = () => {
const [position, setPosition] = useState('test')
useEffect(() => {
// initialMap
const initialMap = new Map({
target: "map",
layers: [
new Tile({
source: new OSM(),
}),
],
view: new View({
center: fromLonLat([15, 50]),
zoom: 8,
}),
})
// pick up coordinates
initialMap.on('click', (e) => {
const coordinate = e.coordinate
const lonLat = toLonLat(coordinate)
// I cant understand, why the next setPosition(lonlat) does not update the cosnt position
setPosition(lonLat)
console.log(position)
})
}, [position]);
return { position }
};```
Solution 1:[1]
SetState is async, so
change:
setPosition(lonLat)
console.log(position)
to:
setPosition(lonLat, () => {
console.log(position)
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Donnle |
