简体   繁体   中英

React-native, firestore: how to update component state when an instance variable changes its value

I'm using Google Firestore as my backend with React Native.

I created a class where I'm storing everything about firestore (methods, info, etc..) and I'm using the real-time updates ( https://firebase.google.com/docs/firestore/query-data/listen ) in that class:

class Fire{
  constructor() {
    this.user = {};  //is defined when the user log in
    this.userDocument = null;
  }

  _getRealTimeData = () => {
    const realTimeDatabaseRef = db.collection("users").doc(this.user.uid);
    realTimeDatabaseRef.onSnapshot(doc => {
      try {
        if (doc.exists) {
         this.userDocument = doc.data();
        } else {
          this.userDocument = null;
        }
      } catch (error) {
        console.log(error);
        this.userDocument = null;
      }
    });
  };
}
Fire = new Fire();
export default Fire;

So this is working fine, whenever I update my firestore database, I automatically get the new value and store it in: this.userDocument

The thing is that when this value changes the react-native component does not update, obviously it is because the state of that component is not updating.

So my question is, how can I notify my component that the value of "this.userDocument" in Fire class has changed? so then I can update the state by this.setState({userDocument: Fire.userDocument}).

Note: Right now I just get the data from "this.userDocument" in componentDidMount():

import Fire, { db } from "../../Fire";
export default class Profile extends Component {
    state={ userDocument:null }
    componentDidMount(){
      Fire._getRealTimeData()
      this.setState({userDocument: Fire.userDocument})
    }
  render(){...whatever I render}
}

a) you can pass a callback to Fire and call it to set state on you Profile component.

b) pass a Promise to Fire component and resolve/reject it to set state to Profile component.

your state at { Profile } change only at componentDidMount, therefore there is nothing that tells to this component that it should be rendered again.

I don't know what is the action that user use to update his profile data at firebase, but at the end of that add something like


  if (this.state.userDocument != Fire.userDocument)
                   this.setState({userDocument: Fire.userDocument})

if the action is at { Profile }, if it is in one of the child send this function and state as props, or of course add Redux to project and then store the state there and connect component to store and it gonna update automatically

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