João Pedro
João Pedro

Reputation: 978

How to get all the documents to use in react?

I'm trying to get all the documents from a collection to display in a react component, I would like to put all the docs in an array I've tried doing this :

export const getProjects = async () => {
  firestore
    .collection("projects")
    .get()
    .then((querySnapshot) => {
      return querySnapshot.docs;
    })
    .catch((e) => {
      console.error(e);
    });
};

but I get undefined, if I do a console.log(querySnapshot.docs) it works.

Upvotes: 0

Views: 42

Answers (1)

fortunee
fortunee

Reputation: 4332

The Problem

You're not returning firestore.collection(...) from the getProjects function, you're only returning it from inside then callback function.

Solution

Return firestore.collection(...) from the getProjects like this

export const getProjects = async () => {
  return firestore
    .collection("projects")
    .get()
    .then((querySnapshot) => {
      return querySnapshot.docs;
    })
    .catch((e) => {
      console.error(e);
    });
};

Upvotes: 1

Related Questions