I'm having troubles setting state to the variable isCorrectAnswer inside an axios call. I'm getting the error Cannot read properties of undefined (reading 'setState') in the console log. What am I doing wrong?
Initial state of isCorrectAnswer variable is constructor(props) {super(props)this.state = { isCorrectAnswer: false }}
and the axios call is
axios.post(
"API/path/to/ressource",
postData,
{
headers: {
"X-Access-Token":
"token",
},
}
)
.then(function (res) {
this.setState({
isCorrectAnswer: res.data.correct //Here im trying to change the state
}, () => console.log(this.state.isCorrectAnswer)) //and logging into console
})
.catch(function (error) {
console.log(error);
});
When you call a function (non arrow function),
thisis always an implicit parameter.Normal functions
By normal functions I mean functions that are not methods.
In strict mode value of
thisis alwaysundefined.And in non strict mode value of
thisis always the global object (windowin browsers)Methods
thisrefers to the object on which the method has been invoked.And in your case the callback passed to
thenis a normal function (not a method), so it'sthisis setundefined, hence you are getting an error.Update to an arrow function and it would solve the issue because arrow functions don't have their own
this, in arrow functionsthisis decided on the basis of lexical scope. Checkout the example below: