Malmi
Malmi

Reputation: 45

How to assign response object to state

I could get data from nodejs backend to react frontend using axios. But I can't assign that object to state object in React.

getData=()=>{
  let responseToHandle;
  axios.get("http://localhost:9000/api/getData")
    .then(function (response) 
     {
      console.log(response.data);//This is working
      responseToHandle = response.data;
      console.log(responseToHandle);//This is working
      this.setState({
        data: responseToHandle}, () => {
        console.log(this.state.data)
        })
      })



// HERE IS MY STATE OBJECT


state={
  data:[]
}

Upvotes: 1

Views: 263

Answers (2)

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

axios call and this.setState are both asynchronous.

You must add your desired code inside a callback:

this.setState({
    data: responseToHandle
}, () => {
    console.log(this.state.data)
    // Now you can use this.state.data
});

Edit:

You also need to change

axios.get("http://localhost:9000/api/getData").then(function (response) { ... })

to

axios.get("http://localhost:9000/api/getData").then(response => { ... })

Without arrow function the scope inside .then() is the function scope, different from component scope, which means using this gives you a different value.

Upvotes: 2

Georgiy T.
Georgiy T.

Reputation: 1211

This code won't work properly:

console.log(this.state.data)

You called a console.log function synchronously right after a promise declaration. Promise works asynchronously.

So in order to check a new state, you should call console.log in render() method, or the best option is to use componentDidUpdate() method.

E.g.

componentDidUpdate(prevProps, prevState) {
  console.log(`Previous data: ${prevState.data}`);
  console.log(`New data: ${this.state.data}`);
}

Upvotes: 1

Related Questions