1

This is a function that i am using to check if a person has already cast a vote. I am using firebase backend.

madeVote() {
  let id = this.state.id
  var userid = this.props.location.state.userid;

  var idRef = database.ref('/voted/' + userid);
  if (id == -1) {
    alert("Please select a candidate")
  } else {

    var idQuery = idRef.child('voted');
    //console.log(userid);
    idQuery.once("value", function(snapshot) {
      console.log("Value " + snapshot.val());
      if (1) {
        alert("You have already voted")
        this.props.history.push('/thanks')
      }
    })
  }
}

'this' is null in line "this.props.history.push('/thanks')".
I understand that I need to bind this. But how do i do that here?.

Devang Naghera
  • 731
  • 6
  • 13
Arshak Anjum
  • 142
  • 1
  • 10

1 Answers1

3

Just use the arrow function.It will automatically bind this to your function

idQuery.once("value", (snapshot)=> {
      console.log("Value " + snapshot.val());
      if (1) {
        alert("You have already voted")
        this.props.history.push('/thanks')
      }
    })
Devang Naghera
  • 731
  • 6
  • 13