1

I am working on a Firebase project in React JS and I need to append the data from the database to an array. When I add to the array like this:

const db = firebase.firestore()
const docData = []
useEffect(() => {
  db.collection("articles").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        docData.push(doc.data())

    });
  });
  console.log(docData)
}, [])

This properly displays the data in the console, however when I return the data outside of the useEffect like this:

return (
    <div className="App">
      {docData}
    </div>
  );

This does not return any array. I am new to React JS and any help would be appreciated.

1 Answer 1

2

You will need to place docData into a state variable so you can update and render it. Declare an array to push into in the promise chain callback and then update the component state.

const [docData, setDocData] = React.useState([]);

useEffect(() => {
  db.collection("articles")
    .get()
    .then((querySnapshot) => {
      const docData = []; // locally scoped to callback
      querySnapshot.forEach((doc) => {
        docData.push(doc.data());
      });
      setDocData(docData); // update state
      console.log(docData);
    });
}, []);

...

return (
  <div className="App">
    {docData}
  </div>
);

An alternative that some may consider more clean would be to map the snapshot data to the array.

useEffect(() => {
  db.collection("articles")
    .get()
    .then((querySnapshot) => {
      const docData = querySnapshot.map((doc) => doc.data());
      setDocData(docData);
      console.log(docData);
    });
}, []);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.