Emilis
Emilis

Reputation: 162

react firestore snapshot not a function

Hi so I followed firebase docs to get data from my collection. But I get error that snapshot is undefined. This is what I tried:

const [data, setData] = useState([]);
    useEffect(() => {
        const db = Firestore.firestore();
        // let tempData = Controller.getData();
        const projects = db.collection('projects');
        const snapshot = projects.get();
        let fireData = [];
        snapshot.forEach((doc) => {
            console.log('data:', doc.data());
            fireData.push(doc.data());
        });

        setData(fireData);
    });

enter image description here enter image description here

I tried TypeError: snapshot.forEach is not a function But then I het data() is undefined plz help

Upvotes: 1

Views: 282

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

projects.get() returns a promise that resolves with a QuerySnapshot object. It doesn't directly return the snapshot. You have to wait for the promise to resolve in order to get the data, as illustrated in the documentation:

        projects.get().then(snapshot => {
          let fireData = [];
          snapshot.forEach((doc) => {
            console.log('data:', doc.data());
            fireData.push(doc.data());
          });
          setData(fireData);
        });

Upvotes: 2

Related Questions