简体   繁体   中英

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

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:

在此处输入图像描述

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

在此处输入图像描述

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

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM