Search code examples
reactjsreact-hooksuse-effectuse-state

How to add to an array in useEffect React JS


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.


Solution

  • 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);
        });
    }, []);