skip to Main Content

At the moment, I’m fetching documents from my firestore collection but if I set an ID generally it won’t return anything, until I hardcode the ID in the Doc, here’s my code…

useEffect(() =>{
    // LISTEN (REALTIME)
    const fetchData = async (id) =>{
      const docRef = doc(db, "users" , "DRrJ5zVL1YdP4wVs32aC");
      const docSnap = await getDoc(docRef);

      if (docSnap.exists()) {
        const theData = docSnap.data();
        console.log('getUserDoc() setting userInfo:', theData);
        setUserInfo(theData);
        console.log("Document data:", docSnap.data());
      } else {
        // docSnap.data() will be undefined in this case
        console.log("No such document!");
      }
    }

    fetchData();
    }, [id]);

I have a lot of documents in my collection and I want to only retrieve the required ID when I’m to update a doc..

2

Answers


  1. If I’m not mistaken what you want to do is fetch the documents without referencing an id.
    For that you will need to use, getDocs() rather than getDoc.
    This will allow you to query a collection of items rather than a single item.
    Here is a snippet from the firebase docs:

    import { collectionGroup, query, where, getDocs } from "firebase/firestore";  
    
    const museums = query(collectionGroup(db, 'landmarks'), where('type', '==', 'museum'));
    const querySnapshot = await getDocs(museums);
    querySnapshot.forEach((doc) => {
        console.log(doc.id, ' => ', doc.data());
    });
    
    Login or Signup to reply.
  2. Did you try const docRef = doc(db, "users" , id)?

    I’m getting the error of, "Cannot read properties of undefined (reading ‘indexOf’)"

    That typically happens if id is undefined. Please debug locally, as the best way to find this out is in the local debugger, by inspecting the variables.

    Set a breakpoint on each line of the code you shared, run the code in a debugger, and then check the value of each variable on each line to determine the first line that doesn’t do what you expect it to do.

    You’ll see that id is empty when you pass it to Firestore.

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