Closed rhoffmann closed 5 years ago
From axios@15 is is possible to pass a cancelToken with each request, to offer the possibility to cancel a pending request/promise. See https://github.com/mzabriskie/axios#cancellation
I implemented a proof of concept and added another dispatchable action type _CANCEL, which checks if the promise has been cancelled. There are currently no tests and an example of a documentation have to be written, as this is not too trivial to use.
export const action = (params) => {
const source = axios.CancelToken.source();
return {
type: 'ACTION',
payload: {
request: {
...,
source,
cancelToken: source.token,
}
}
};
};
Basically you would need to pass a cancelToken
for each request, as well as the source object itself. The source object will be needed as a reference to cancel with source.cancel('reason')
. The source needs to be created per request, as it will otherwise will be is cancelled
state in following requests. Your 'ACTION' reducer should take care of storing the source somewhere in your state.
You could then cancel your request with something like this:
export const cancel = () => (dispatch, getState) => {
const source = getState().source; // or with selectors
source.cancel('cancelled');
};
The middleware will then dispatch by default ACTION_CANCEL
, which you can use to update your state tree accordingly. The dispatch payload will in addition to the error object have a cancelled
property.
I guess this could be simplified for the user if the middleware itself takes care of creating the token and source by itself for each request, so every request is by default cancellable. Or this could be configured per request with isCancellable: <bool>
.
I just wanted to check if this is something which will be needed (i think it is) and if i should pursue this further. Comments are welcome. :)
@rhoffmann is this project dead? :/
She is alive and well :)
As with any OS project, the maintainers are usually busy but always willing to accept completed PRs.
Has there been any progress on this? It seems that there's currently no way to even check if a request has been canceled if you handle all the token stuff yourself.
Thank you for your support
starting to implement handling of axios cancelToken handling to dispatch _CANCEL action