简体   繁体   中英

How do I read information from Firebase and use it in a React component?

I'm trying to read some information from a document in my database on Firebase using the web SDK and display that information in a React component. Here's the flow of my work:

render() {
let db = firebase.firestore();
let docRef = db.collection('user').doc('name');
docRef.get().then(doc => {
    console.log(doc.data());
});
return (
// HTML using data from doc.data()
);
}

However, I can't get the info from doc.data() outside of the callback in the .then() call. How can I use the data from doc.data() outside the callback, and render it back in React?

see edited lines marked with //

render() {
  let myData; //
  let db = firebase.firestore();
  let docRef = db.collection('user').doc('name');
  docRef.get().then(doc => {
    myData = doc.data(); //
  });
return myData; //
// or html involving myData
}

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