Can't fetch firebase collection with React

女生的网名这么多〃 提交于 2021-02-08 10:07:50

问题


I'm using React hooks + firebase.

In firebase, I created a collection called "projects"

When I try to console log the data with:

const Dashboard = () => {
  const { firebase } = useContext(GlobalContext);

  return (
    <div className="container">
      {console.log(firebase.db.collection("projects"))}
    </div>
  );
};

I'm getting the following object:

Shouldn't be able to see my data?

Below are my firebase and context set up

firebase.js

import app from "firebase/app";
import "firebase/auth";
import "firebase/firebase-firestore";

const config = {//mydata}

class Firebase {
  constructor() {
    app.initializeApp(config);
    this.auth = app.auth();
    this.db = app.firestore();
  }
}

export default new Firebase();

context.js

import React, { useReducer } from "react";
import { projectReducer } from "./reducers";
import firebase from "../components/firebase/firebase";

export const GlobalState = props => {
  const [projects, setProjects] = useReducer(projectReducer, []);

  return (
    <GlobalContext.Provider
      value={{
        projects,
        firebase
      }}
    >
      {props.children}
    </GlobalContext.Provider>
  );
};

回答1:


The key of how you interact with Firestore in your code seems to be:

firebase.db.collection("projects")

This code creates a reference to the projects collection in Firestore. It does not retrieve any data from the database yet.

To get data, you need to attach a listener to the collection. From the Firestore documentation on getting documents from a collection:

db.collection("cities").where("capital", "==", true)
    .get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            // doc.data() is never undefined for query doc snapshots
            console.log(doc.id, " => ", doc.data());
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });

You'll need to do something similar in your code.

Typically in React projects, you'll store the data in the component's state by calling setState(...) in the then() callback, and then render the content from the state in your JSX.



来源:https://stackoverflow.com/questions/55561358/cant-fetch-firebase-collection-with-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!