Hi I am having a fetch interceptor to catch some common responses like 401 etc... When response status is equal to 401. I need to dispatch logout action inside the interceptor itself. But i am not able to make it. Dispatch action is not working. Here i am sharing the code of what i have done. Please help me to fix that.
import fetchIntercept from 'fetch-intercept';
import { pushToDataLayer } from './GTMUtility';
import configureStore from '../redux/configureStore';
import { LoggedOut } from "../redux/auth/actions";
const getEndPointFromURL = (url = '') => {
if (!url) return;
const urlSegments = url.split('/')
return urlSegments[urlSegments.length - 1];
}
const store = configureStore();
export const interceptor = fetchIntercept.register({
request: function (url, config) {
return [url, config];
},
requestError: function (error) {
// Called when an error occured during another 'request' interceptor call
return Promise.reject(error);
},
response: function (response) {
if (response.status === 401) {
store.dispatch(LoggedOut());
return false
}
return response;
},
responseError: function (error) {
// Handle an fetch error
return Promise.reject(error);
}
});
Exporting Store:
import { createStore, applyMiddleware, compose } from "redux";
import rootReducer from "./rootReducer";
import createSagaMiddleware from "redux-saga";
import { fromJS } from "immutable";
export default function configureStore(initialState = {}) {
const sagaMiddleware = createSagaMiddleware();
const middlewares = [sagaMiddleware];
const composeEnhancers =
typeof window === "object" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
// Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
})
: compose;
return {
...createStore(
rootReducer,
composeEnhancers(applyMiddleware(...middlewares))
),
runSaga: sagaMiddleware.run
};
}
Thanks in advance.
In your interception register file, you must also export that store for other files to use it. If you also call const store = configureStore()
somewhere else, that's creating a totally new instance of store. Then the store.dispatch
used by interceptor is not gonna affect the other instance of store, thus your problem.
I suggest that, instead of exporting configureStore
function, you create the store right inside that file and export it.
export const store = configureStore()
Then in the interceptor file:
import { store } from '../redux/configureStore';
Same to other files that need a store. Don't create it again.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.