I have a map displaying a geoJSON layer using react-leaflet. I am dynamically changing whats rendered using leaflet-draw.
I am using a loop to find the layers which dont meet the criteria, then saving them so i can add them back later as per the code below.
const [removedLayers, setRemovedLayers] = useState([]);
const [removedMarkers, setRemovedMarkers] = useState([]);
const onCreatePolygon = (e) => {
const geojsonLayers = ref.current;
let [tempLayers, tempMarkers] = [[], []];
//remove polygons that meet criteria
geojsonLayers.eachLayer((layer) => {
if (!e.layer.contains(layer.getCenter())) {
tempLayers.push(layer);
layer.remove();
}
});
//remove markers that meet criteria
const markerGroup = markerRef.current;
markerGroup.eachLayer((layer) => {
if (!e.layer.contains(layer.getLatLng())) {
tempMarkers.push(layer);
layer.remove();
}
});
e.layer.remove();
setRemovedLayers(tempLayers);
setRemovedMarkers(tempMarkers);
return "";
};
The problem is both removedLayers and removedMarkers are empty. I understand it's async so its not instant but it seems no matter how long i wait, its still empty.
Which leads me to think the setState is being executed while the for loop is still running. Adding more hooks seems convoluted, what is the best way to solve this?