3

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?

2
  • What error do you get? The code looks fine and should set songList
    – Dharmaraj
    Oct 24, 2021 at 10:55
  • songList is an array, but when I set my "songs" state with songList, songs!=songList (see console image)
    – nghihua
    Oct 24, 2021 at 11:07

1 Answer 1

1

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

1
  • Thanks to your comment, I've realized the real (dumb, very dumb) problem! Turns out I use the name "states" for two different variables, one is the ColletionReference you said above, and the other is a State (first line in my code)
    – nghihua
    Oct 24, 2021 at 11:43

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.