I have the next problem:
export async function updateLessons() {
let data
await database().goOnline().then(async () => {
await database()
.ref('days')
.on('value', snapshot => {
console.log(snapshot.val())
data = snapshot.val();
});
});
return data;
}
I use this function to update my application when I swipe down
const onRefresh = React.useCallback(async () => {
setRefreshing(true);
setLessons(await updateLessons());
console.log(lessons)
setRefreshing(false);
}, []);
It is called from scroll view (refreshcontrol)
The problem is that it doesn't work asynchronously. In console log i see my snapshot. But the application updated faster and in console.log(lessons) it is undefined. How can I fix it?
Updating state is an asynchronous operation, and won't have completed yet by the time your console.log statement runs.
A simple way to get the correct output, is to capture the new lessons in local variable (which is updated synchronously):
const onRefresh = React.useCallback(async () => {
setRefreshing(true);
const newLessons = await updateLessons();
setLessons(newLessons);
console.log(newLessons)
setRefreshing(false);
}, []);
Also see:
useEffect hook to respond to state changes.