Oliver
Oliver

Reputation: 1181

How to set state in React after successful Firebase set?

I have the following function to save my app's state to a Firebase ref:

saveResultsToDatabase() {

    const {
      companyName, companyUrl, productName, goals, industries,
      ageRanges, gender, other, weightedScores, goalScores, industryScores, ageScores, recommendation,
      email, phone, optin
    } = this.state

    const databaseObject = {
      companyName, companyUrl, productName, goals, industries,
      ageRanges, gender, other, weightedScores, goalScores, industryScores, ageScores, recommendation,
      email, phone, optin
    }


    contactRef.push().set((databaseObject), function(error) {
      if (error) {

        console.log(error)
      } else {
        this.setState({savedToDatabase: true})
      }
    })

I want to update the "savedToDatabase" object in my state on successful Firebase execution. However, this does not work. I get the following error:

TypeError: Cannot read property 'setState' of undefined

What am I missing here?

Upvotes: 0

Views: 506

Answers (1)

Geraint
Geraint

Reputation: 3392

Inside the function() {} of the callback for for firebase action this is different to the this of the component. One option is to use an arrow function instead which binds to the context of this.

You can read more about this here: https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4

e.g.

contactRef.push().set((databaseObject),(error) => {
  // do something
  this.setState({})
}

This should work.

Another option which you might've seen previous is by using var self = this approach

var self = this;
contactRef.push().set((databaseObject), function(error) {
  // do something
  self.setState({})
}

Upvotes: 1

Related Questions