0
constructor(){
  super();
  this.state = {
     data: ''
  }
}


axios.post('/user', {
  firstName: 'Fred',
  lastName: 'Flintstone'
})
.then(function (response) {
  console.log(response);
   this.setState({data: response });  // here i am getting error
   console.log(this.state.data);
})
.catch(function (error) {
  console.log(error);
});

In My react native app i am not able to setState the ajax response.. When i am trying to update the state here it throws error and execute catch function... I don't know why it happens can you please give me the quick suggestion

Manikanta
  • 325
  • 6
  • 20

2 Answers2

0

That's because you use the ES2015 syntax to create your function, which doesn't bind the context by default. Use an arrow function instead :

.then((reponse) => {
    console.log(response);
    this.setState({data: response });
    console.log(this.state.data);
}
0

First of all, please read the difference between arrow functions and normal function declarations.

this.setState({}) will only work if you use arrow functions () => or you can do it the old fashion way by saving this inside a variable like so:

fetchData() {
    const self = this;
    axios.post('/user', {
      firstName: 'Fred',
      lastName: 'Flintstone'
    })
    .then(function (response) {
      console.log(response);
       self.setState({data: response });  // here i am getting error
       console.log(self.state.data);
    })
    .catch(function (error) {
      console.log(error);
    });
}

I, however, prefer to use an arrow function instead as it's much simpler.

ex:

fetchData() {
    axios.post('/user', {
      firstName: 'Fred',
      lastName: 'Flintstone'
    })
    .then(response => this.setState({data: response }) )
    .catch(console.log);
}

P.S: You can also bind this using the .bind(this) method.

Ray
  • 9,184
  • 3
  • 27
  • 44