Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

89
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda