how set errors from laravel in vuejs - laravel

I am trying to retrieve errors from Laravel in Vue, but i get this error message in my console "Cannot set property 'errors' of undefined".
I have tried different approaches like direct assignment of errors and the $set() of vue to set error message to the error object of my data function, but it is still in vain.
This is my code
export default{
data(){
return{
form: {},
errors:{}
}
},
methods:{
async onSave() {
await Api().post('/stocks/store',this.form)
.then()
.catch(function (error) {
if(error.response && error.response.status == 422) {
let errors = error.response.data.errors;
// this.$set(this.$data.errors,'errors',errors)
console.log(errors);
this.errors = errors;
}
});
}
}
This is how the error message from my console
This is the error message from laravel
how do set this.errors with error message from laravel

If you look closely at the error, it says
Cannot set property 'errors' of undefined
So the problem is you are trying to set a property of an undefined object, in this case: this, your Vue component.
An easy and convenient way to solve this problem is to use arrow function instead of a regular function in your Promise.catch() callback. To put simply, a regular function expression has his own this context, where arrow function does not.
Here is a sample of code that should help you understand better:
new Promise().then()
.catch((error) => {
if(error.response && error.response.status == 422) {
this.errors = error.response.data.errors;
}
});
To learn more about arrow function and the binding of this

Related

error Policy in Apollo Client React does'nt work

I have aproblem when test Apollo.When I try query with apollo and graphql, i want response return error and partical data, so I set property errorPolicy:'all'. But its not work. I don't no why? Help please!
Here my code:
query { animal {
name
age }, school {
name
numberfd } } `
const { loading,data,error} = useQuery(GET_DASHBOARD_DATA, {
errorPolicy:'all',
onCompleted: (res) => {console.log("complete",res)},
onError : (res,data) => {console.log("ERRRR",res,data)},
})
and i want to receive:
{
error:[...], data:[animal:[...]] }
but its only response error.Here is Apollo's doc: https://www.apollographql.com/docs/react/data/error-handling/
onError type is onError?: (error: ApolloError) => void;. You don't have data inside onError callback.
After useQuery you can add:
console.log('data', data)
console.log('error', error)
I faced the same issue with errorPolicy: 'all', I only received the partial result inside onCompleted callback of useQuery, but no errors.
I created an ErrorLink like this:
private createErrorLink = () => {
return new ApolloLink((operation, forward) => {
return forward(operation).map((response) => {
// filter out errors you don't want to display
const errors = filterSomeErrors(response.errors);
if (errors && response?.data) {
response.data.errors = errors;
}
return response;
});
});
};
Now inside my onCompleted callback I get my data as well as errors. You will have to tweak your types a bit, because seems there is no errors field on response.data by default.
Mind that if you use onError from Apollo and return something from the link, it will retry your request containing errors!

get user permissions with laravel vue rest api

I'm trying to get all user permissions with Laravel for backend and vuejs for frontend.
How can i get this from api to vue? what is the best choice?
I tried to get them with below code but shows me error
In the permissionMixin:
import PermissionDataService from '../../Servieces/PermissionDataService'
export default {
methods: {
checkPermission() {
let permissions;
PermissionDataService.get("user_permissions")
.then((response) => {
permissions= response.data;
})
.catch((error) => {
console.debug(error)
});
return hasAccess;
}
}
}
and that is how i used it in main.js:
import permission from "#/core/mixins/permissionMixin";
Vue.mixin(permission);
window.Laravel = this.checkPermission();
console.debug(Laravel)
Vue.directive('can', function (el, binding) {
return Laravel.permissions.indexOf(binding) !== -1;
});
but always shows me this error:
Uncaught TypeError: can't access property "defaults", a.default.axios is undefined
I am totally sure the endpoint is ok
ANY Idea?
Finally solved.
I had to put
window.Laravel = this.checkPermission();
into one of layout files

How to commit to store within a SetTimeOut in VueJS

I am making an app in Laravel using Vue.js. I would like to wait two seconds when a method is triggered and then execute a store action. However, when I implement this I receive an error.
Here is my code:
.listen('TeamLeaving', e => {
setTimeout(function() {
axios.get('/api/team/' + e.team.id + '/pulse').then(response => {
if (response.data === 0) {
// here is where it messes up
this.$store.commit('team/REMOVE_TEAM', e.team)
}
})
}, 2000)
// this.$store.commit('team/REMOVE_TEAM', e.team);
})
However I get an error:
Uncaught (in promise) TypeError: Cannot read property 'commit' of undefined
When I do the commit outside of the setTimeout it works just fine. So I am assuming there is a problem inside the setTimeout. Could someone help me maneuver this?
This post might help you: how to set timeout in a vueJs method
The important bit:
this in anonymous function is attached to that anonymous function
not to your main function
You can try this:
.listen('TeamLeaving', (e) => {
let vm = this;
setTimeout(function () {
axios.get('/api/team/'+ e.team.id + '/pulse')
.then(response => {
if (response.data === 0) {
//here is where it messes up
vm.$store.commit('team/REMOVE_TEAM', e.team)
}
});
}, 2000);
// this.$store.commit('team/REMOVE_TEAM', e.team);
});

Nuxt.js and Laravel Api - 422 Displaying Error instead of Forms

[Error][1]
Hi Team,
Whenever I am receiving the error return from laravel the nuxt.js project displays the error on the page instead the HTML/Forms. How can i handle this.
Here is my php code
return response()->json([
'errors' => [
'email' => ['Sorry we cant find you with those details.'],
],
], 422);
Javascript
async submit() {
await this.$auth.loginWith("local", {
data: this.form
})
In your JavaScript you need to wrap your await promise inside a try catch block. Here's a fix for your JS.
try {
await this.$auth.loginWith("local", {
data: this.form
})
} catch (e) {
return;
}
This is an old question at this point, but I thought I'd post the full code since I was pretty stumped and didn't find many great answers out there:
async handleSubmit() {
try {
const authResponse = await this.$auth.loginWith('local', {
data: this.formData
});
const { status, data } = authResponse;
if (status === 200)
this.createFlashAlert({ 'success': 'Login successful' });
} catch (error) {
if (error.response.status === 422)
this.createFlashAlert(error.response.data);
}
}
So the checklist:
Wrap the login call in a try/catch if you're using async await syntax (be sure to make it an async function i.e. async handleSubmit.
in the catch block, use the error.response object, this is an axios thing. With this you'll be able to access the response status and data.
If you log just the error object, it's not obvious that you can access the response within that error which is what had me stumped.

Show Modal on AngularJS $httpProvider: responseError

We need to hookup a Modal with a generic message on our failed Ajax calls in AngularJS.
i was able to intercept the error on the app.config part, but from there i am unable to import the $modal or the $scope to show the modal. What i got working so far is creating a function on my global scope and add the opening of the modal in my app.run:
var showGeneralException = function () { };
var app= angular.module('myApp', ['ui.bootstrap'])
.run(function ($rootScope, $modal) {
showGeneralException = function () {
var exceptionModel = $modal.open({
templateUrl: 'generalException',
controller: 'exceptionModals',
});
};
});
app.config(function ($httpProvider) {
$httpProvider.interceptors.push(function ($q) {
return {
'responseError': function (rejection) {
showGeneralException();
}
};
});
});
When i perform it this way a modal opens but i get a not found exception in my modal and following errors in my debug console:
TypeError: Unable to get value of the property 'data': object is null or undefined
LOG: WARNING: Tried to load angular more than once.
LOG: WARNING: Tried to load angular more than once.
LOG: WARNING: Tried to load angular more than once.

Resources