zahabba
zahabba

Reputation: 3231

React Native: undefined is not an object (evaluating '_this.setState')

I'm at a bit of a loss why I'm getting this error message in the simulator with the code below. The line # is indicated in a comment.

this.setState seems to be in the correct object format.

  fetchData: function() {
    fetch(apiUrl)
      .then((response) => response.json())
      .then((responseData) => {
        this.collectResponses(responseData);
      })
      .then((responseObject) => {
        this.sortPredictions(responseObject);
      })
      .then((predictionsObj) => {
        this.setState({   // ERROR HERE!
          castroInKTLM: predictionsObj['5728'],
          churchInKTLM: predictionsObj['5726'],
          churchInJ: predictionsObj['4006'],
          churchInN: predictionsObj['4448'],
          montgOut: predictionsObj['6994'],
          church37In: predictionsObj['7073'],
          church37Out: predictionsObj['5667'],
          castro37Out: predictionsObj['3325'],
          castro33In: predictionsObj['3255'],
          fetchTime: predictionsObj['fetchTime']
        });
      })
      .done();
  },

Upvotes: 0

Views: 4086

Answers (1)

Lee Gary
Lee Gary

Reputation: 2397

I have not done react-native yet, but i believe the error you are seeing, is due to this not within the function scope (the one that receives predictionsObj) as parameter

fetchData: function() {
    var self = this;
    fetch(apiUrl)
      .then((response) => response.json())
      .then((responseData) => {
        this.collectResponses(responseData);
      })
      .then((responseObject) => {
        this.sortPredictions(responseObject);
      })
      .then((predictionsObj) => {
          self.setState({   
          castroInKTLM: predictionsObj['5728'],
          churchInKTLM: predictionsObj['5726'],
          churchInJ: predictionsObj['4006'],
          churchInN: predictionsObj['4448'],
          montgOut: predictionsObj['6994'],
          church37In: predictionsObj['7073'],
          church37Out: predictionsObj['5667'],
          castro37Out: predictionsObj['3325'],
          castro33In: predictionsObj['3255'],
          fetchTime: predictionsObj['fetchTime']
        });
      })
      .done();
  },

Upvotes: 2

Related Questions