While trying to update the state from a function and calling the function from componentdidmount
lifecycle method, the state doesn't update.
But when I try to update the state by calling the function from inside the jsx, it does work. I dont know what is happening
//my state
constructor(){
super()
this.state = {
activepage:'dashboard',
language:[],
}
}
//the function I am updating state from
getLanguage = () => {
axios.get('http://localhost:3001/language')
.then(function (response) {
console.log(response.data.language);
this.setState({
language:response.data.language
})
})
.catch(function (error) {
return error;
});
}
//I am calling function from
componentDidMount(){
this.getLanguage();
console.log("state after updating",this.state) //displays an empty array
}
But when I call function getLanguage
from inside the jsx it updates the state.