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

90
Visualizações
how to setState for an array of fulfilled promises

In my react app, I am retrieving some data from firebase , but when I try to store the items in my state it stores only the first item of the fulfilled promises ,

const HomePage = (props) => {
  const [events ,setEvents] = React.useState([])
const fetchGames=async()=>{
    const DB =await db.collection('game').get()

    DB.docs.forEach(item=>{
      setEvents([...events,item.data()])
      console.log(item.data()); // Here shows all the items that stored in my firebase collection
     })
    }
    
    useEffect(()=>
    {
      fetchGames()
    }, [])
return(
<div>
{
     events.map((event)=>
        (
          <div>
            {event.home_color}
          </div>

        )
        )
    }
</div>
)

Eventually the events state will display only one item , unlike in the console log which displayed all the items , how to fix this?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

React state is not synchronous. So updating state in a for loop does not guarantee every iteration you will get an updated state.

You can prepare the final object in the forEach & then update state once it has finished. Something like -

const fetchGames=async()=>{
    const DB =await db.collection('game').get()
    const eventsFromDb = [];
    DB.docs.forEach(item=>{
      // update eventsFromDb array here 
    })
    // set state here
    setEvents(eventsFromDb);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Repeatedly calling setEvents in your forEach loop does not allow for the state to actually be updated because the React useState hook is not synchronous.

You could do something like this:

setEvents([ ...events, ...DB.docs.map(item => item.data())])

Assuming the data() method isn't async - sorry I don't know Firebase.

about 4 years ago · Juan Pablo Isaza Relatório
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