0

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!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
CSStudent123456
  • 173
  • 1
  • 4
  • 16

1 Answers1

2

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:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807