So I’m trying to use React Query with Firestore and usually this works pretty fine but recently I have been unable to make a function that returns a value.
const fetchProduct = async () => {
const querySnapshot = await getDocs(collection(db, "notes"));
const arr = [];
querySnapshot.forEach((doc) => {
setNotes(doc.data())
}).catch((error) => {
console.log(error);
return null;
});
return notes
}
I’m later trying to use this function with React Query like this –
const { isLoading, isError, data, error } = useQuery(['todos'], fetchProduct)
However the value of the {data} always return to undefined but however once the fetchProduct()
function is called manually it all works.
Is there anything I’m missing or doing wrong?
2
Answers
Setting the state is an asynchronous operation in React (see docs), so the value of
notes
isn’t set yet by the time yourreturn notes
runs.If you want to return the value synchronously:
More typically though, you’ll want to put the code that depends on that return value into its own
useEffect
hook that depends on thenotes
state.Also see:
It should be like this, you should not set inside the foreach function
Note: don’t use variable name as doc in foreach, instead use some other variable name like since doc is built in function of firebase you might have imported it