0

I have an html element that needs to updated every time there is a change in Firebase. What I've done so far is this implement this particular function:

componentWillMount() {
    var that = this;
    var updateDb = firebase.database().ref("currentToken");
    updateDb.on("value", function(snapshot) {
        that.setState({ currentToken: snapshot.val() });
    });
    console.log(that.state.currentToken);
    document.getElementById("tokenField").innerHTML = "Current Token: " + that.state.currentToken;
}

What is the proper way to update a variable in my app whenever there is a change in Firebase? Kindly give any suggestion to improve my coding as I'm a beginner.

1 Answer 1

1

One thing that stands out to me is how you're handling this. You should be able to use a arrow function to maintain scope:

updateDb.on("value", (snapshot) => {
  this.setState({ currentToken: snapshot.val() });
});

The other thing that stands out is

document.getElementById("tokenField").innerHTML =
  "Current Token: " + that.state.currentToken;

React will not update that element when you call setState. React will update any components requiring state by calling the render method. I don't know what the rest of your code looks like, but assuming that is a component that you are rendering, you should update it in render like this:

<div id="tokenField">
    Current token {this.state.currentToken}
</div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.