This is the first time I try to use React Native (expo) with FireBase, and I have many difficulties on async calls.
now I'm trying to retrieve some data with 2 calls to FireBase (I don't know if this is correct).
useEffect(() => {
let isMounted = true;
if (isMounted) {
let exercies1 = {};
db.ref("trainings_exercies/" + trainingID + "/exercies").on(
"value",
(snapshot) => {
if (snapshot && snapshot.val()) {
Object.keys(snapshot.val()).map((e) => {
db.ref("exercies/" + e).on("value", (snapshot) => {
for (let key in snapshot.key) {
exercies1[snapshot.key] = snapshot.val();
}
setExerciesList(exercies1);
console.log("---> ", exercies1);
});
});
}
}
);
}
return () => {
isMounted = false;
};
}, []);
and I have this in my return:
{console.log("exercies", exerciesList)}
this is the console, the component first prints the console log inside the return, but then when it sets the new status, it does not update the component:
only the e001 element has been added before moving forward.
how can I fix this? and how can I handle calls to FireBase so that I wait for an answer before setting the statuses?
thank you very much for your help, if you need more information, I can also upload the whole code.
The last line of your code }, []);
that empty array []
makes the useEffect hook to run only once.
As far as I can tell I don't see you are use a state object, in you were you could call useEffect at the end like }, [state]);
and it will be triggered every time the state changes.
Try removing the []
from the hook, it should make react re-render the component if it detects a change.
The line
return () => {
isMounted = false;
};
Is a cleanup method that will only be triggered once the component is discarted/unmounted so the code inside the useEffect hooks will never get isMounted = false
Most of this is very well documented on the react website
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.