In my functional component I'm using useState hook twice, and then useEffect with the first state variable as the only dependency. The useEffect is only executed on the initial render even if it's dependency is successfully changed.
Another weird thing is that I can only change the newPolygonCoords (by using the setNewPolygonCoords) but I can't change the drawnPolygonCoords. The set functions are both run in a nested function, but only one of them work.
export default function LeafletMap(props) {
const [newPolygonCoords, setNewPolygonCoords] = useState([])
const [drawnPolygonCoords, setDrawnPolygonCoords] = useState([[0.0,0.0]])
useEffect(() => {
alert("USEEFFECT")
console.log("USEFFECT")
}, [newPolygonCoords])
(...)
function DrawComponent(props) {
const map = useMapEvents({
click(e) {
console.log("DrawComponent(), newPolygonCoords = " + newPolygonCoords)
console.log("DrawComponent(), drawnPolygonCoords = " + drawnPolygonCoords)
if (!props.inDrawState) return // do nothing if not in draw state
const newNewPolygonCoords = newPolygonCoords
newNewPolygonCoords.push(e.latlng.lat+","+e.latlng.lng)
setNewPolygonCoords(newNewPolygonCoords)
if (newPolygonCoords.length === 0) {
setDrawnPolygonCoords([[0.0,0.0]]) // make sure drawnPolygonCoords is never empty
}
else {
console.log("drawComponent(), else block")
console.log("DrawComponent(), newPolygonCoords = " + newPolygonCoords)
console.log("DrawComponent(), drawnPolygonCoords = " + drawnPolygonCoords)
setDrawnPolygonCoords(newPolygonCoords)
console.log("DrawComponent(), setDrawnPolygonCoords(newPolygonCoords) has been executed.....??")
console.log("DrawComponent(), drawnPolygonCoords = " + drawnPolygonCoords)
}
}
})
return null
}
(...)
}
So the set functions are called when the user clicks on the leaflet map. Here's my output:
DrawComponent(), newPolygonCoords =
DrawComponent(), drawnPolygonCoords = 0,0
drawComponent(), else block
DrawComponent(), newPolygonCoords = 55.7105901514022,12.567765250964833
DrawComponent(), drawnPolygonCoords = 0,0
DrawComponent(), setDrawnPolygonCoords(newPolygonCoords) has been executed.....??
DrawComponent(), drawnPolygonCoords = 0,0
So clearly the setNewPolygonCoords works, but not the setDrawnPolygonCoords. I receive no error... Help is much appreciated :)