Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

90
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda