How to update Firebase data to the React application in realtime

旧巷老猫 提交于 2021-02-12 09:23:20

问题


I'm developing an application that updates Firebase data in realtime to React. What I want to do is that a user updates the state in the app, at the same time it should be updated for another user.

I have built it done but it continually renders renderStatus() and it's too slow. I want to make it updated once RDB data updated.

class Status extends Component {
  constructor(props) {
    super(props);
    this.state = {
      to_status: false,
      from_status: false
    };
  }

  // change the state in RDB
  handleSatus = () => {
    const { post } = this.props;
    firebase
      .database()
      .ref("/busy/" + post.uid)
      .set({
        status: true,
        last_changed: firebase.database.ServerValue.TIMESTAMP
      });
    this.setState({ to_status: true });
  };

  renderStatus() {
    const { post } = this.props;
    const { to_status, from_status } = this.state;

    // fetch the data in RDB
    let self = this;
    firebase
      .database()
      .ref("/busy/" + post.uid)
      .once("value")
      .then(function(snapshot) {
        self.setState({ from_status: snapshot.val().status });
      });

      if (this.state.from_status) {
        return (
          <p>Updated</p>
        );
      } else {
        return (
          <p>Not updated yet</p>
        );
      }
  }

  render() {
    return (
      <div>
        {this.renderStatus()}
        <button onClick={this.handleStatus()}>Click!</button>
      </div>
    )
  }

回答1:


You'll typically want to:

  1. Register an on() listener in your componentDidMount() method.
  2. Call setState with the relevant data from the database, when that initially loads and when it changes.
  3. Let react handle the rendering from the state as usual.

So something like:

componentDidMount() {
  firebase
    .database()
    .ref("/busy/" + posy.uid)
    .on("value")
    .then((snapshot) => {
      this.setState({ from_status: snapshot.val().status });
    });
}
render() {
  return (
    <div>
      <p>{this.state.from_status?"Updated":"Not updated yet"}</p>
      <button onClick={this.handleStatus()}>Click!</button>
    </div>
  )
}


来源:https://stackoverflow.com/questions/59871401/how-to-update-firebase-data-to-the-react-application-in-realtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!