Reputation: 15464
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
Upvotes: 1
Views: 1568
Reputation: 11
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.
Upvotes: 0
Reputation: 568
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);
})
});
}
Upvotes: 3
Reputation: 5243
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
.
Upvotes: 2