KshitijV97
KshitijV97

Reputation: 397

Unable to dispatch redux actions in axios success response interceptor

Usually we dispatch actions in Axios error response interceptor and it works fine

axiosInstance.interceptors.response.use(
    (next) => {
        return Promise.resolve(next);
    },
    (error) => {
// Dispatching to handle error 1
        if (error.response.status === 401) {
            if (error.response.data.errorCode === 'USER_LOGIN_ERROR_008') {
                store.dispatch({ type: 'RESET_SECURITY_QUESTION', payload: { id: null, qid: null, question: null } });
            }
     throw error;
    }
);

Every successful API response sets a token in user's cookies and if no API is called in the next X minutes then that token will expire

So after every successful API response I need to start a timer in my App.js and once that timer ends would show a Modal to the user that his session has been invalidated

However if a user's actions result in successful API calls then I want to reset that timer

To reset that timer I would want to call a redux action after every successful API response

So this is what I tried to do

axiosInstance.interceptors.response.use(
    (next) => {
        console.log(`Intercepting ${next.config.url} success response`, next);
        if (next.status === 200) {
             store.dispatch(incrementSessionRefreshTimer());
        }

        return Promise.resolve(next);
    },

There is an problem here

Whenever we use axios interceptor to intercept success request, We can modify the request and have to return the request back

What happens in my code is that my action is dispatched but the response is never returned, No lines below store.dispatch(myAction()) are executed and hence the Component in which I made an API call does not get the success response

Any workaround for this?

Upvotes: 0

Views: 743

Answers (1)

phry
phry

Reputation: 44078

The code should definitely continue executing after that dispatch. It might cause an immediate rerender, in which case the rerender might happen before the next line, but unless an exception is thrown anywhere, that return Promise.resolve(next); line will execute. I think your problem lies elsewhere.

Upvotes: 1

Related Questions