skip to Main Content

I have issue with error response from axios client to my useMutation.

axios client

import axios from "axios";

const client = axios.create({ baseURL: `${process.env.REACT_APP_API_HOST}/${process.env.REACT_APP_API_PREFIX}` });

export const request = ({...options}) => {
    client.defaults.headers.common.Authorization = `Bearer ${JSON.parse(localStorage.getItem('userDetails')).idToken}`
    client.defaults.headers.common['Content-Type'] = 'application/json';
    const onSuccess = (response) => {
        console.log('AXIOS !!!!! request Successful!!!', response.config.url)
        return response;
    };

    const onError = error => {
        console.error('AXIOS !!!!!  Request Failed:', error.config.url);
        return error
    };

    return client(options).then(onSuccess).catch(onError);
}

this is my useMutatuon file

import { useMutation, useQueryClient } from 'react-query';
import {request} from '../utils/axios';

const useAddInvestmentAction = (investment)  => {
    // Define the headers object
    return request({ 
        url: '/investments/investment1', 
        method: 'post', 
        data: investment,
    })
}


export const useAddInvestmentData = () => {
    const queryClient = useQueryClient()
    return useMutation(useAddInvestmentAction,{
        onSuccess: () => {
            queryClient.invalidateQueries('InvestmentsData')
            console.log('Investment Added Successfully!!!!!!!!!!!!!!!!!')
        },
        onError: (error) => {
            console.log('Investment Failed!!!!!!!!!!!!!!!!!')
            console.log(error)
        }
    })
}

export default useAddInvestmentData;

when I change my url to not exist uri my onSuccess trigger and not my onError. The Axios print onError

any idea why?

2

Answers


  1. In your request method you first catch the error and then you are returning the response of the error, not the error. Due to this the request is marked as successful. You will have to throw the error in order to forward the error.

    In onError you can throw a new Error

    export const request = ({...options}) => {
        client.defaults.headers.common.Authorization = `Bearer ${JSON.parse(localStorage.getItem('userDetails')).idToken}`
        client.defaults.headers.common['Content-Type'] = 'application/json';
        const onSuccess = (response) => {
            console.log('AXIOS !!!!! request Successful!!!', response.config.url)
            return response;
        };
    
        const onError = error => {
            console.error('AXIOS !!!!!  Request Failed:', error.config.url);
            throw new Error(error)
        };
    
        return client(options).then(onSuccess).catch(onError);
    }
    

    Also few suggestions:

    1. useAddInvestmentAction: This isn’t a hook. Just a method to add investment action. Just name it something like addInvestmentAction

    2. request: This method waits for a response using then. Better to make this method async.

    3. Better to use interceptors for implementing onSuccess and onError

    Login or Signup to reply.
  2. You need to throw an error from the catch block. Also, remember that the catch block like then returns a promise unless an error is thrown.

        const onError = error => {
            console.error('AXIOS !!!!!  Request Failed:', error.config.url);
            throw new Error('error_mesage') // <- this is the change
        };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search