Skip to content

Instantly share code, notes, and snippets.

@mb8z
Created October 2, 2018 14:48
Show Gist options
  • Save mb8z/6c22abfbaa2f4a3e95a52952a318519a to your computer and use it in GitHub Desktop.
Save mb8z/6c22abfbaa2f4a3e95a52952a318519a to your computer and use it in GitHub Desktop.
// I described my problem on https://stackoverflow.com/questions/52607886/react-requests-cancellation-on-page-change/52610800#52610800
// and worked my way through it
import _ from 'lodash';
import axios from 'axios';
// history should be imported from a file where it's created
import { history } from '../app/setup';
class RequestCancelation {
static constants = {
cancelationTokens: 'CANCELATION_TOKENS',
}
getTokens() {
return _.get(window, RequestCancelation.constants.cancelationTokens, {});
}
setTokens(tokens) {
return _.set(window, RequestCancelation.constants.cancelationTokens, tokens);
}
deleteTokens(key) {
if (!key) return undefined;
delete window[RequestCancelation.constants.cancelationTokens][key];
return this.getTokens();
}
getLocationKey() {
return _.get(history, 'location.pathname');
}
getCancelToken(type) {
return new axios.CancelToken((c) => {
const cancel = c;
if (typeof window === 'undefined') return;
const tokens = this.getTokens();
if (type) {
tokens[type] = cancel;
} else {
const key = this.getLocationKey();
if (!key) return;
if (!tokens[key]) tokens[key] = [];
tokens[key].push(cancel);
}
this.setTokens(tokens);
});
}
cancelRequest(type) {
if (!type) {
return console.warn('#cancelRequest - please specify \'type\'');
}
if (typeof window === 'undefined') return undefined;
const tokens = this.getTokens();
const cancel = tokens[type];
if (!cancel) return undefined;
cancel();
return this.deleteTokens(type);
}
cancelRequests() {
if (typeof window === 'undefined') return undefined;
const tokens = this.getTokens();
const key = this.getLocationKey();
if (!key) return undefined;
const cancels = tokens[key];
if (!cancels) return undefined;
cancels.forEach(cancel => cancel());
return this.deleteTokens(key);
}
clearTokens() {
if (typeof window === 'undefined') return undefined;
window[RequestCancelation.constants.cancelationTokens] = {};
return this.getTokens();
}
}
const cancelation = new RequestCancelation();
export default cancelation;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment