简体   繁体   中英

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

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 :

控制台图像在这里

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM