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

89
Views
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 answers
Answer question

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 Report

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 Report
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!