skip to Main Content

I am using Laravel and Vue3 with axios to handle user inputs and save data to database.
If there is a validation error then I want to display a toast error to user.

For some reason the response from axios put function is undefined if Laravels validation fails.
I have tried all the other fixes I found on the net but am still getting undefined.

My axios instance:

const instance = axios.create({
    baseURL: import.meta.env.VITE_API_BACKEND_URL,
    withCredentials: true,
    headers: {
        Accept: `application/json`,
    },
});

Function which calls Laravel (Api is the axios instance created above):

async confirmOrder(order: splicingPurchaseOrderType) {
   Api.put(`/splicing_purchase_orders/${order.id}`, {
      ...order,
   }).then((response: any) => {
      console.log(response);
   });

Function which gets called in Laravel:

public function put(SplicingPurchaseOrder $splicingPurchaseOrder, Request $request): JsonResponse
{
   $validated = $request->validate([
      'pallets' => 'required|numeric',
      'quality_id' => 'required|exists:AppDomainQualityModelsQuality,external_id',
      'specie_id' => 'required|exists:AppDomainSpecieModelsSpecie,external_id',
   ]);

And a screenshot of the actual response from browsers dev tools:
Screenshot of dev tools network tab

What am I missing?

I can just use if(!response) and display some generic error but that does not seem right and I have displayed Laravel validation errors just fine before. But at the moment I do not understand what is going on, should be a trivial task but I am failing.

I read that others have been mixing await and .then() together and that has caused the issue but that does not seem to be the issue I am facing. Tried const response = await Api.put…

Tried wrapping validate in try catch block in Laravel and write a return myself, still the same issue.

Must be a simple thing, I am just not seeing it.

2

Answers


  1. Chosen as BEST ANSWER

    Never mind, found the issue.

    I had interceptor also in place, to handle the NProgress behaviour.

    Interceptor on response looked like this:

    instance.interceptors.response.use(
        (response) => {
            callCount.value--;
            return response;
        },
        (error) => {
            callCount.value--;
        }
    );
    

    The error died there. Added return to make the interceptor look like this:

    instance.interceptors.response.use(
        (response) => {
            callCount.value--;
            return response;
        },
        (error) => {
            callCount.value--;
            return Promise.reject(error);
        }
    );
    

    Now I am getting the expected behaviour from Axios.


  2. Axios methods return a Promise that is resolved only when the response’s status code is between 200-299 inclusive. For any other status code, the Promise would be rejected.

    In your case, since the status code is 422, you can use either of these snippets to handle your error:

    Using async/await:

    async confirmOrder(order: splicingPurchaseOrderType) {
      try {
        const res = await Api.put(`/splicing_purchase_orders/${order.id}`, {
          ...order,
        });
        console.log(res.data); // Success response
      } catch (error) {
        console.log(error.response.data); // Error response
      }
    }
    

    Using Promise.then/catch:

    confirmOrder(order: splicingPurchaseOrderType) {
      Api.put(`/splicing_purchase_orders/${order.id}`, {
        ...order,
      })
        .then((res) => console.log(res.data)) // Success response
        .catch((error) => console.log(error.response.data)); // Error response
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search