Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
789 views
in Technique[技术] by (71.8m points)

reactjs - How to update Firebase data to the React application in realtime

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>
    )
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...