Mithrandir
Mithrandir

Reputation: 21

Loading when fetching firestore data

I want to set a loading state whenever the page is fetching the firestore data . I am using this :

 const [isLoading, setIsLoading] = React.useState(true)
const fetchGames=async()=>{
    let promises = []
    const dataDB = await db.collection('event')
    const eventsFromDb = []
    const DB =await db.collection('event').get()
    DB.docs.forEach((item,index)=>{
      const promise = dataDB
      eventsFromDb[index]= item.data()
      promises.push(promise);
     })
     setEvents(eventsFromDb)
     Promise.all(promises)
     .then(setIsLoading(false));
    }
useEffect(()=>
    {
      fetchGames()
      if(!isLoading)
      {
        console.log("HEY")
      }

    }, [])

I cannot get the HEY in my console , how to fix this ?

Upvotes: 1

Views: 72

Answers (1)

silencedogood
silencedogood

Reputation: 3299

As it stands, your useEffect method only runs on component mount. You need it to run when state is updated as well.

You just need to add your state as a parameter within the useEffect array argument. Like so:

useEffect(()=>
{
  fetchGames()
  if(!isLoading)
  {
    console.log("HEY")
  }

}, [isLoading])

This will run the effect on mount and when the isLoading state is updated.

Upvotes: 1

Related Questions