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

234
Visualizações
React: Cannot get state slice to update, but other state properties work fine

Using these two pieces of state:

this.markerArray = [];
this.arrayLength = 0;

I am trying to use this function:

getMarkers = () => {
  this.dbRef.get().then((snapshot) => {
    snapshot.docs.forEach((marker) => {
      if (!this.markerArray.includes(marker.id)) {
        let currentID = marker.id;
        let appObj = {
          ...marker.data(),
          ["id"]: currentID,
        };
        this.markerArray.push(appObj);
      }
    });

    this.setState({
      markerArray: this.markerArray,
    });
    // (problem code) this.setState({arrayLength: this.markerArray.length})

    return this.markerArray;
  });
};

To update a list of map markers. I am trying to update this.arrayLength when this.markerArray's length changes. I think the problem has to do with setState's asynchronous nature, but I can't figure out what to do with that information.

I have tried:

  1. Creating a separate function to set arrayLength
  2. Passing that function as a callback when setting markerArray's state
  3. Calling the function in Render (infinite loop)
  4. Setting arrayLength in the same setState as markerArray
  5. Changing the initial value of arrayLength to null, 0, and ''

I have even tried setting arrayLength to an arbitrary number that does not rely on markerArray.length, but it won't update.

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