reactjs axios interceptors how dispatch a logout action

You could include this interceptor code in the same place you have access to the redux store directly. Maybe in the file that you create your redux store (index.js)?

With that in place, you can dispatch the action directly from the redux store like that:

import reduxStore from './store';

import App from './components/App';

const router = (
  <Provider store={reduxStore}>
    <Router>
      <Route path="/" component={App}/>
    </Router>
  </Provider>
);

/** Intercept any unauthorized request.
* dispatch logout action accordingly **/
const UNAUTHORIZED = 401;
const {dispatch} = reduxStore; // direct access to redux store.
axios.interceptors.response.use(
  response => response,
  error => {
    const {status} = error.response;
    if (status === UNAUTHORIZED) {
      dispatch(userSignOut());
    }
   return Promise.reject(error);
 }
);

render(router, document.getElementById('app-root'));

I got the same issue with you and this is my solution:

  1. Define axios interceptors and call redux store.
import Axios from 'axios';

const interceptor = (store) => {
    Axios.interceptors.request.use(
        (conf) => {
            if(!conf.headers['Authorization']){
                
            }
            console.log(store);
            debugger;
            // you can add some information before send it.
            // conf.headers['Auth'] = 'some token'
            return conf;
        },
        (error) => {
            debugger;
            return Promise.reject(error);
        }
    );
    Axios.interceptors.response.use(
        (next) => {
            debugger;
            return Promise.resolve(next);
        },
        (error) => {
            // You can handle error here and trigger warning message without get in the code inside
            
            debugger;
            return Promise.reject(error);
        }
    );
};
const store = createStore(reducer, enhancer);
interceptor(store);
  1. Config redux store into your project.
  2. Call axios request:
function getAllCompany(userObject) {

    let headers = { 'Authorization': 'Bearer ' + userObject.accessToken }

    return axios({
        method: 'post',
        url: rootURL + "/getallcompany",
        data: { },
        headers: headers
    }).then(handleResponse).catch(handleError);
}

Tags:

Reactjs

Axios