Alfrex92
Alfrex92

Reputation: 6778

Can't fetch firebase collection with React

I'm using React hooks + firebase.

In firebase, I created a collection called "projects"

enter image description here

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:

enter image description here

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>
  );
};

Upvotes: 0

Views: 1177

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598887

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.

Upvotes: 2

Related Questions