skip to Main Content

I’m trying to dispatch a redux toolkit action inside an axios response interceptor.

I’ve seen some other question suggesting people to use store.dispatch(somefunction())

In redux toolkit you usually call the useDispatch() hook to dispatch an action, but since its a hook I can’t call it inside of my non-component axios intercept function.

myaxios.js

import axios from 'axios'
const BASE_URL = 'http://localhost:8080'
export const myaxios = axios.create({
  baseUrl: BASE_URL
})

axiosWithIntercept.js (shortened to scope of question):

import { myaxios } from './myaxios'
myaxios.interceptors.response.use(resp => resp, async (err) => {
  if (err?.resp?.status === 401) {
    // run my dispatch action here
  }
})
export default myaxios

2

Answers


  1. import { myaxios } from './myaxios';
    
    export const myaxiosFunc = (dispatch,storeActions) => {
        myaxios.interceptors.response.use(resp => resp, async (err) => {
            if (err?.resp?.status === 401) {
                // run my dispatch action here
                dispatch(storeActions.yourMethodName());
            }
        })
    
    }
    
    export default myaxiosFunc;
    
    Login or Signup to reply.
  2. You can use in this way too.

    import store from './path-to-your-redux-store'; // Update the path accordingly
    .
    .
    .
    myaxios.interceptors.response.use(resp => resp, async (err) => {
      if (err?.response?.status === 401) {
        // Dispatch your Redux action here
        store.dispatch(yourReduxAction());
      }
      return Promise.reject(err);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search