简体   繁体   中英

How to get Firebase Cloud Firestore data in one line that returns one value in React Native

I am trying to get data from a firebase cloud firestore database in one line in a Text component in react native. Here is what I am trying to do:

...
<Text style={styles.name}>
 {firebase.firestore().collection("users").doc(post.uid).get().name}
</Text>
...

This code is trying to place a value in a React Native Text component by fetching a document with id "post.uid" so that the document data is returned where the value "name" is called and returns a single string. I would appreciate any help on how to do this as I am not able to figure out the solution. Thank you in advance!

The closest you can get is by using await

(await firebase.firestore().collection("users").doc(post.uid).get()).data().name

I recommend studying the Firestore documentation on getting data carefully, and trying to get the value outside of your render function first.


Update

Since you're using react, I'd highly recommend taking this approach:

  1. In your componentDidMount start loading the data.
  2. Once the data is loaded call setState() to add it to the state.

    Combined these look like:

     componentDidMount() { firebase.firestore().collection("users").doc(post.uid).get().then((doc) => { this.setState({ name: doc.data().name }); } }
  3. Then render the data from the state.

     <Text style={styles.name}> {this.state.name} </Text>

Also see:

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