Home > Back-end >  Why I can't set state to Firebase's doc data?
Why I can't set state to Firebase's doc data?

Time:10-24

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?

CodePudding user response:

"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()).

  • Related