skip to Main Content

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


  1. Setting the state is an asynchronous operation in React (see docs), so the value of notes isn’t set yet by the time your return notes runs.

    If you want to return the value synchronously:

    return querySnapshot.docs.map((doc) => doc.data());
    

    More typically though, you’ll want to put the code that depends on that return value into its own useEffect hook that depends on the notes state.

    Also see:

    Login or Signup to reply.
  2. It should be like this, you should not set inside the foreach function

    const fetchProduct = async () => {
      const querySnapshot = await getDocs(collection(db, "notes"));
      const notes = [];
      querySnapshot.forEach((note) => {
        notes.push({ ...note.data(), id: note.id })
      }).catch((error) => {
          console.log(error);
          return null;
      });
      return notes;
    }
    
    // in the place of the calling the function
    const notes = await fetchProduct();
    setNotes(notes);
    

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search