Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

88
Views
React setState doesnt work in react-leaflet update

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!