Home > Software engineering >  Realtime data collection in firestore referenced by id rather than the whole collection?
Realtime data collection in firestore referenced by id rather than the whole collection?

Time:02-24

I am trying to grab a single doc from firestore from a collection that could have a thousand unrelated data.

My issue is I am getting the whole pack. Can I reference by a particular id?

I don't a user to get other user info in to his front end. I am using a custom hook. Can I use collection(db, col) with doc id?

import React, { useContext, useEffect, useRef, useState, useMemo } from 'react';
// DB
import { db } from '../../firebase';
import { collection, onSnapshot } from 'firebase/firestore';

export const dataCollection = (col: any) => {
  const [data, setData] = useState<any>(null);

  useEffect(() => {
    let colRef = collection(db, col);
    const unsub = onSnapshot(colRef, (snapShot) => {
      let results: any = [];
      snapShot.docs.forEach((doc) => results.push(doc.data()));
      console.log(results, 'LOG RESULTS');
      setData(results);
      return () => unsub;
    });
  }, [col]);

  return { data };
};

CodePudding user response:

Firestore's onSnapshot function is quite versatile and can work on an entire collection reference, a query for a subset of the documents in a collection (group), or a single document.

If you want to read a document and know its ID, you can do that with:

const colRef = collection(db, col);
const docRef = doc(colRef, 'your document ID here');
const unsub = onSnapshot(docRef, (doc) => {
  let results: any = [doc.data()];
  console.log(results, 'LOG RESULTS');
  setData(results);
  return () => unsub;
});
  • Related