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),
this
is always an implicit parameter.Normal functions
By normal functions I mean functions that are not methods.
In strict mode value of
this
is alwaysundefined
.And in non strict mode value of
this
is always the global object (window
in browsers)Methods
this
refers to the object on which the method has been invoked.And in your case the callback passed to
then
is a normal function (not a method), so it'sthis
is 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 functionsthis
is decided on the basis of lexical scope. Checkout the example below: