I've had this problem for a while and tried everything I could think of but so far I haven't found anything to solve this yet. When fetching data from my database I set my loading state to true and when I'm done I set it back to false, now the problem is that it never gets set to true. In the code example, I've delayed the fetch for 5 seconds so that it simulates slow internet to see the loading indicator and state change if it would work.
Edit: I'm using firebase firestore to get my data. to be more specific I use onsnapshot listener which is not asynchronous so I can't use async. I also removed the try-catch block since this has no use either, yet still, the loading state is not set to true before I call the database.
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
try {
setTimeout(() => {
//fetchting from database.
}, 5000);
return () => {
/* unsubscribe(); */
};
} catch (error) {
console.log(error);
} finally {
setLoading(false);
}
}, []);
Edited function:
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
setTimeout(() => {
firebase.db
.collection("collectionname")
.onSnapshot((snapshot) => {
//handeling data returned.
})},
5000
);
setLoading(false);
return () => {
/* unsubscribe(); */
};
}, []);