0

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.

Abdullah
  • 2,015
  • 2
  • 20
  • 29
Asim Dahal
  • 147
  • 2
  • 11

2 Answers2

0

update your function with es6 arrow function

.then((response) => {
        console.log(response.data.language);
        this.setState({
            language:response.data.language
        })
    })
M Usman Nadeem
  • 415
  • 2
  • 13
0

For es6 you can use arrow function

getLanguage = () => {
    axios.get('http://localhost:3001/language')
        .then((response) => {
            console.log(response.data.language);
            this.setState({
                language:response.data.language
            })
        })
        .catch((error) => {
            return error;
        })
    );
}

For es5 you can declare this out of scope axios function

function getLanguage() {
    var self = this;
    axios.get('http://localhost:3001/language')
        .then(function(response) {
            console.log(response.data.language);
            self.setState({
                language:response.data.language
            })
        })
        .catch(function(error) {
            return error;
        })
    );
}
jayyzdayo
  • 3
  • 3