1

I'm a little stuck developing my application. So far im able to connect to the Firestore db and get my documents. My plan is to fetch the data from each document and store it in an array. From there i will display it.

The issue im having is that the results from the first time render wont add the elements to the array. DATA.push() method works but its not saved outside of this forEach loop? Thanks!

const data is where the document ref is stored.

const DATA = [] is the array.

const [data, setdata]= useState([{}]);

useEffect(() => {
  const getUsers = async () => {
    const data = await getDocs(usersCollectionRef);
    data.forEach(doc =>{

      DATA.push({id: doc.id, title: doc.data().Type, status: doc.data().status, location: doc.data().Location, type: doc.data().Type, injured: doc.data().Injured, collar: doc.data().Collar, color: doc.data().Colour })
    
    })
    
  };

  getUsers();
  console.log(dataNew);
 
}, []);
const DATA = [];

Example

2
  • What is difference in data old and data new? Also in which var the data from firestore query goes ? Commented Mar 7, 2022 at 9:03
  • @Dharmaraj The query is stored in const data = await getDocs(usersCollectionRef); Commented Mar 7, 2022 at 9:25

1 Answer 1

1

You can just map data from all documents in an array, set that in state and render it. Try refactoring the code as shown below:

const [data, setData]= useState([]);

useEffect(() => {
  const getUsers = async () => {
    const snapshot = await getDocs(usersCollectionRef);

    const data = snapshot.docs.maps(d => ({ id: d.id, ...d.data() }))
    console.log(data);

    setData(data);
  };

  getUsers();
}, []);


return(
  <div>
    { 
      data.map((d) => {
        <p>{ d.id }</p>
      })
    }
  </div>
)
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.