Reputation: 519
i'm trying to use VueJS and Axios to make an HTTP request to a Laravel backend to get some JSON and then use the JSON to update an errorMessage property on my Component.
Axios.post('/api/login', {
email: this.email,
password: this.password
}).then((response) => {
this.errorMessage = response.message;
}).catch((error) => {
console.error(error);
})
The problem is that it's not being able to reference this.errorMessage
for some reason, am i doing anything wrong here? I'm correctly making the HTTP request and the JSON response comes back just as expected if i console.log
it, but when i try to manipulate this.errorMessage
it says that it's undefined even though i've already manipulated it with success elsewhere...
Here is the entire code for this component
export default {
methods: {
submitForm: function(e) {
e.preventDefault();
Axios.post('/api/login', {
email: this.email,
password: this.password
}).then((response) => {
debugger;
this.errorMessage = response.data.message;
}).catch((error) => {
console.error(error);
});
}
},
data: function() {
return {
errorMessage: null,
email: null,
password: null
}
},
components: {
'error': Error
}
}
SOLUTION:
The original request is correct, fat arrow functions should keep the value of this
, the issue was with Chrome's Debugger, which showed the values to me as undefined
even though they weren't... Sorry for the silly question, i hope this will help other people coming across this kind of issue.
Upvotes: 3
Views: 5367
Reputation: 4885
Axios.post is closer function so property define within it looks like private under closer function.
You have to define variable outside closer like this :
//this will pick your data.
let self = this;
Axios.post('/api/login', {
email: this.email,
password: this.password
}).then((response) => {
self.errorMessage = response.message;
}).catch((error) => {
console.error(error);
})
Also if response.message
is undefined then use response.body.message
or the returning variable from laravel.
Upvotes: 14
Reputation: 219920
The response's data is available under the data
property:
this.errorMessage = response.data.message;
Upvotes: 0