While fetching some data from firestore, I am setting a loading state , but this state will return to true once again , I don't know why :
const [isLoading, setIsLoading] = React.useState(true)
nprogress.start()
const fetchGames=async()=>{
const eventsFromDb = []
const DB =await db.collection('event').get()
DB.docs.forEach((item,index)=>{
eventsFromDb[index]= item.data()
})
setEvents(eventsFromDb)
setIsLoading(false)
console.log(isLoading) // consoling this will return true after the progress is done(false)
}
useEffect(()=>
{
fetchGames()
if(!isLoading)
{
nprogress.done()
}
}, [isLoading])
How can I fix this ? after it finished loading it starts over again
CodePudding user response:
React sets its state asynchronously so right after setting the state can still be true
Try it like this
useEffect(() => {
fetchGames()
}, [])
useEffect(() => {
if (!isLoading) {
nprogress.done()
}
}, [isLoading])
CodePudding user response:
I fixed this issue , by just ordering the code , since I was setting the Loading after I store the data in an array :
const fetchGames=async()=>{
const eventsFromDb = []
const DB =await db.collection('event').get()
DB.docs.forEach((item,index)=>{
eventsFromDb[index]= item.data()
})
setIsLoading(false) // This will be replaced above the setEvents
setEvents(eventsFromDb)
console.log(isLoading) //
}