I saw this blog post the other day, and I think the second part describes what you are looking for. You do not necessarily want to cancel requests, but ignore the responses.
Basically, you want to create an external reducer that will track your asynchronous server requests with unique identifiers. Only if the request identifier is in the list, then allow it to sub-reducers.
When you switch the page, you want to delete this list of unique identifiers.
Raised directly from the blog:
const initialState = []; function update(state = initialState, action) { const { seqId } = action; if (action.type === constants.UNLOAD) { return initialState; } else if (seqId) { let newState; if (action.status === 'start') { newState = [...state, seqId]; } else if (action.status === 'error' || action.status === 'done') { newState = state.filter(id => id !== seqId); } return newState; } return state; }
and then restrict the sub-reducers:
let store = createStore((state, action) => { if (action.seqId && (action.status === 'done' || action.status === 'error') && state && state.asyncRequests.indexOf(action.seqId) === -1) { return state; } return reducer(state, action); });
Big shout to James for that. A really nice solution and is very well explained in his blog post.
source share