I am developing a query to an api using axios with react . The responses arrive correctly but I am not being able to update the status of a variable, which shows errors from the server or correct login
In the console, it tells me that the this operator is undefined.
The code of my function is the following:
consumirApiLogin() {
const payload={
"_username":this.state.username,
"_password":this.state.password,
}
axios.post(API_LOGIN, payload)
.then(function (response) {
this.setState({errorApi: response.data})
})
.catch(function (e) {
console.log(e);
let error = '';
if(e.response)
{
let error = e.response.message;
}
this.setState({errorApi: error})
});
}
My constructor is the following:
constructor(props){
super(props);
this.state = ({
username:'',
password:'',
errors: {},
errorApi: ''
})
this.cambioUsername = this.cambioUsername.bind(this);
this.cambioPassword = this.cambioPassword.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.consumirApiLogin = this.consumirApiLogin.bind(this);
this.validarFormulario = this.validarFormulario.bind(this);
}
Any help is welcome! Greetings!
It looks like you missed some JavaScript concepts before you started with React and one of these is the one that is giving you trouble.
In JavaScript, every function (not arrow function) has a container or bag known as a context or scope . When you use
this
inside a function you are actually referencing this container or higher containers (chaining). In this case, you are making use ofthis
within a callback , a callback does not have a parent context, sothis
it will always refer to the same context as the callback.It's actually doing something like:
Because as I explained above, this refers to the context in which it is called. What do you have to do to solve the problem?
Simple, convert your callback to arrow function :
Same for him
catch
.