how to cancel previous axios with redux in react
You would need access to the source
variable in order to cancel it.
Alternatively you could cancel the previous request when you create a new one (this seems to be your use case).
Something like the following (using the executor function syntax: https://github.com/axios/axios#cancellation so you get a new token for each request)
import axios from 'axios';
import $ from 'jquery';
var CancelToken = axios.CancelToken;
let wj_cancel, wjc_cancel;
export const FETCH_WORKERJOBS = 'fetch_workerjobs';
export function fetchWorkerJobs(page, size, where, sort) {
wj_cancel && wj_cancel();
const request = axios.get(`/api/user/report/comms/matrix/upload/format/json?quiet=1&page=` + page + `&size=` + size + `&where=` + JSON.stringify(where) + `&sort=` + sort, {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
wj_cancel = c;
}
});
return {
type: FETCH_WORKERJOBS,
payload: request
};
}
export const FETCH_WORKERJOBS_COUNT = 'fetch_workerjobs_count';
export function fetchWorkerJobsCount(where) {
wjc_cancel && wjc_cancel();
const request = axios.get(`/api/user/report/comms/matrix/upload/count/format/json?quiet=1&where=` + JSON.stringify(where), {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
wjc_cancel = c;
}
});
return {
type: FETCH_WORKERJOBS_COUNT,
payload: request
};
}
Here is code that can be used:
// get info in component
useEffect(() => {
const cancelToken = customAxios.CancelToken.source();
dispatch(fetchStream(match.params.id, cancelToken.token));
return () => {
cancelToken.cancel(`Cancel fetchStream ${match.params.id}`)
}
}, []);
// where fetchStream in store/actions/streams.js
export const fetchStream = (id, cancelToken) => async dispatch => {
try {
const {data: stream} = await axios.get(`/streams/${id}`, {
cancelToken
});
dispatch({
type: FETCH_STREAM,
payload: stream
})
} catch (e) {
console.log("fetchStream get error ", e);
}
};