1

I would like to have a general way to show the errors. I tried to add a response interceptor, but my state does not get updated.

interceptor.js

import {showError} from "./actions";
const axiosInstance = axios.create();

axiosInstance.interceptors.response.use(
    response => response,
    error => {
        showError(error);
    }
);

export default axiosInstance;

actions.js

export const showError = (error) => {
    return ({
        type: SHOW_ERROR,
        payload: error.response
    })
}

reducer.js

const INITIAL_STATE = {errorData: ''};

const reducer = (state = INITIAL_STATE, action) => {
    switch (action.type) {
        case SHOW_ERROR:
            return {
                ...state,
                errorData: action.payload.data.translationKey,
            }
    }
}

I have all the imports in place, I can see the error in the actions, but my state does not get updated. Reducer is not called.

Is there a way to update the state directly from the interceptor? I want to avoid catching errors for each api call.

Tom Bom
  • 1,589
  • 4
  • 15
  • 38
  • 1
    I guess u need to dispatch the action rather than directly trying to call it. Also have a look at this link https://stackoverflow.com/questions/52946376/reactjs-axios-interceptors-how-dispatch-a-logout-action – Rukshán Dikovita Jul 15 '21 at 05:53

2 Answers2

3

Try using dispatch like below:

import {showError} from "./actions";
import reduxStore from './store'; << your redux store

const axiosInstance = axios.create();
const {dispatch} = reduxStore;

axiosInstance.interceptors.response.use(
    response => response,
    error => {
        dispatch(showError(error));
    }
);

export default axiosInstance;
  • 1
    useDispatch can't be used outside of a component – Daniel Duong Jul 15 '21 at 06:07
  • 1
    @DanielDuong yes, you are right. I have edited it to instead use store dispatch – Rukshán Dikovita Jul 15 '21 at 06:18
  • @Rukshán redux dev tools shows the update, but for some reason when i log the state it doesn't change. Any idea why that might be happening? If I catch an error where I make a request (not in the interceptor) it works fine – Tom Bom Jul 15 '21 at 14:58
  • are you using console.log ? I guess its not working with redux store. try redux-logger instead. https://stackoverflow.com/questions/36534182/react-native-with-redux-state-changes-not-showing-in-console – Rukshán Dikovita Jul 15 '21 at 15:11
0

If you are using redux Thunk as a middelware

export const showError = (error) => dispatch => {
    return ({
        type: SHOW_ERROR,
        payload: error.response
    })
}
Vishal Kank
  • 41
  • 2
  • 8