Search code examples
javascriptfirebasereact-nativegoogle-cloud-firestorereact-native-firebase

Reading a specific data from firestore document and placing it as a text component


I am currently learning how to implement firestore into a react native expo project and I am just getting started. Firstly, I updated a specific data to a document in my firestore and now I am reading it into the log console, which is the code below.

However, I wish to read only a specific data of the document, such as "height", and place it in the Text component below. Unfortunatly my attempts were unsuccessfull. Could you give me a little help here?

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import * as firebase from 'firebase';
import 'firebase/firestore';

var firebaseConfig = {
  apiKey: "****",
  authDomain: "****",
  databaseURL: "****",
  projectId: "****",
  storageBucket: "****",
  messagingSenderId: "****",
  appId: "****"
};

//Initialize firebase
if (!firebase.apps.length) {
  //If app hasn't initialize, initialize app
    firebase.initializeApp(firebaseConfig);
} 

export default class App extends React.Component{

  componentDidMount() {
    var db = firebase.firestore();
    var docRef = db.collection("users");
    
  let getDoc = docRef.doc('Tiago').get()
    .then(doc => {console.log('Document data:', doc.data())});
}

  render(){
    return (
      <View style={styles.container}>
       <Text>I wish to place it here</Text>
      </View>
    );
  }
}

  const styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
    },
});

Plus, I can't really find a complete documentation on how to implement firestore/firebase into a react native + expo project. Could you leave a link below so I can learn from?


Solution

  • It was a missing this. to render the method.

    export default class App extends React.Component{
    
      componentDidMount() {
        var db = firebase.firestore();
        var docRef = db.collection("users");
        
        let getDoc = docRef.doc('Tiago').get().then(doc => {
          console.log('Document data:', doc.data())
          this.setState({ height: doc.data().height });
        });
      }
    
      render(){
        return (
          <View style={styles.container}>
           <Text>{this.state.height}</Text>
          </View>
        );
      }
    }