Reputation: 97
I'm trying to push a new screen to display the selected item's detail, when I get the data it fetches the document correctly, however if I try to set my object to use it in my screen it is undefined, but if I reload the app it does populate the object, here's the code:
const [event, setEvent] = useState();
const getEvent = async (dbx) => {
const eventDoc = doc(dbx, 'events', eventId);
try {
const eventSnapshot = await getDoc(eventDoc);
if(eventSnapshot.exists()) {
const fetchedEvent = eventSnapshot.data();
setEvent(fetchedEvent);
} else {
console.log("Document does not exist")
}
} catch(error) {
console.log(error)
}
return;
}
useEffect(
()=>{
getEvent(db)
console.log("Event Here: ", event);
}
,[])
Upvotes: 0
Views: 103
Reputation: 600006
Setting a variable in the state is an asynchronous operation. In fact, so is loading data from Firestore, so neither of those operations is done by the time your console.log("Event Here: ", event)
runs.
If you want to log the event value, use another effect that depends on that state variable to do so:
useEffect(()=>{
console.log("Event Here: ", event);
},[event])
Upvotes: 1