Home > database >  Firebase TypeError: querySnapshot.forEach is not a function in React
Firebase TypeError: querySnapshot.forEach is not a function in React

Time:02-27

I'm integrating firebase with React for the first time and I am just following the documentation, this is the code given in the firebase cloud firestore getStarted section:

enter image description here

but when I have tried to copy the same code it gives me an error of TypeError: querySnapshot.forEach is not a function

enter image description here

I'm basically trying to get the data from a collection, document.

here is the code that I have copied:

import React, { useState, useEffect, useRef } from "react";
import { db } from "./firebase.config.js";
import * as firestore from "firebase/firestore";
export default function App() {
    const addEntry = () => {
        try {
            const docRef = firestore.addDoc(firestore.collection(db, "users"), {
                first: "Alan",
                middle: "Mathison",
                last: "Turing",
                born: 1912,
            });
            console.log("Document written with ID: ", docRef.id);
        } catch (e) {
            console.error("Error adding document: ", e);
        }
    };
    const querySnapshot = firestore.getDocs(firestore.collection(db, "users"));
    console.log(querySnapshot);
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });

return (
    <div>
        <button onClick={addEntry}>add</button>
    </div>
   );
}

How can I solv this error

CodePudding user response:

The getDocs() returns a promise and might not have resolved when you are trying to read the docs. Try refactoring the code as shown below:

firestore.getDocs(firestore.collection(db, "users")).then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });
});

Also you can just import getDocs() instead of using namespaces like V8 SDK:

import { getDocs } from "firebase/firestore";
  • Related