Why I can't set state to Firebase's doc data?

0

Issue

I fetch data from my firestore database like thus:

const [songs, setSongs] = useState();

async function getSongs() {
  const songs = collection(db, 'songs');
  const songSnapshot = await getDocs(songs);
  const songList = songSnapshot.docs.map(doc => doc.data());
  setSongs(songList);
  console.log(songList);
  console.log(songs);
};

If I run this, there are two objects in the console, the first one is songList, and the second one is songs:

console image here

Why is there a difference between the two? What do I do to turn songs back into an array?

Solution

"songs" is a CollectionReference and does not contain the data. "songList" is an array which contains data from the documents returned by getDocs(). You should set songList in your state instead of songs

From the documentation,

A CollectionReference object can be used for adding documents, getting document references, and querying for documents (using query()).

Answered By – Dharmaraj

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More