subhashchandru
subhashchandru

Reputation: 97

Cannot able to push elements into the array

state = { driverid: '', history: [{}] }

constructor(props) {
  super(props);
}

componentDidMount(){

  this.setState({ driverid: this.props.navigation.getParam('driverid', 'NO-ID') }, 
   () => {
    const GameScore = Parse.Object.extend("Booking");
    const query = new Parse.Query(GameScore);
    query.equalTo("driverid", this.state.driverid);
    query.find().then(function (results) {
      console.log("Successfully retrieved " + results.length + " scores.");

      for (var i = 0; i <= results.length; i++) {
        this.state.history.push(results.get(results[i]))
      }
      console.log(this.state.history)
    });
  });
}

I'm not able to push elements into the array when executed, the above program gives the following error

WARN Possible Unhandled Promise Rejection (id: 0): TypeError: undefined is not an object (evaluating 'this.history.push')

Upvotes: 0

Views: 29

Answers (2)

Ragib Huda
Ragib Huda

Reputation: 127

First of all, I think you have not handled the promise rejection. Changing the state will handle with this.setState() is the best practice and the state should be writing like this. This would be a help for you I think

constructor(props) {
  super(props);
  this.state = { driverid: '', history: [{}] }
}


query.find().then((results) => {
  console.log("Successfully retrieved " + results.length + " scores.");

  for (var i = 0; i <= results.length; i++) {
    this.setState({history:this.history.push(results.get(results[i]))})
  }
  console.log(this.state.history)
}).catch((error)=>console.log(error);

Upvotes: 0

I can see two thing which could cause your problem. First, do not mutate state like this: this.state.history.push(results.get(results[i])) you should always change state using this.setState to avoid bugs in the code.

Second try to write callback in then as an arrow function. Using normal function probably changed value of this so this.state may be something different now.

Upvotes: 1

Related Questions