Home > OS >  Loading when fetching firestore data
Loading when fetching firestore data

Time:05-27

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 ?

CodePudding user response:

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.

  • Related