1

I need to update the state variable from ajax response. I tried below

componentDidMount() {
   var parent_object=this;
          axios.get('/template.php')
                  .then((result)=> {
                      console.log(result.data);

   parent_object.setState({component_template:result.data})//not updating

                  });

    console.log("here");
    console.log(this.state.component_template);
}

I can see the array for result.data but the state variable component_template is not updated

I tried How to set state of response from axios in react and https://daveceddia.com/ajax-requests-in-react/ but no luck

sumit
  • 15,003
  • 12
  • 69
  • 110

3 Answers3

3

React setState is asynchronous! You can call a callback function after the state value has updated:

componentDidMount() {
      axios.get('/template.php')
              .then((result)=> {
               console.log(result.data);
                this.setState({component_template:result.data},()=>{
                   console.log(this.state.component_template);
                 })

      });

}

f.jafari
  • 568
  • 3
  • 10
2

From the docs:

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.

So the state might be updating properly, but your console.log might not be able to read the updated value. Try using the callback, or check inside componentDidUpdate .

Community
  • 1
  • 1
palsrealm
  • 5,083
  • 1
  • 20
  • 25
0

setState in react is a asynchronous call. Console after the setSate doesn't guarantee the updated value.

Add console either as callback with setState or inside the render method as a first line to check the updated state value.