Axios Cancel Token

Util to handle axios request cancellation logic

Keeping a Map of request-id -> cancel-source

// cancelTokenUtils.ts
import axios, {CancelToken, CancelTokenSource} from 'axios';

const cancelSources = new Map<string, CancelTokenSource>([]);

function cancelLastRequest(requestId: string): void {
  const token = cancelSources.get(requestId);
  if (token) {
    token.cancel();
  }
}

function getCancelToken(requestId: string): CancelToken {
  cancelLastRequest(requestId);
  const nextCancelSource = axios.CancelToken.source();
  cancelSources.set(requestId, nextCancelSource);
  return nextCancelSource.token;
}

export {getCancelToken, cancelLastRequest};

Use

function getAccessToken(token: string): Promise<{token: string}> {
  return client({
    method: 'post',
    url: '/v1/auth/signin',
    data: {token},
    cancelToken: getCancelToken('session.login'),
  });
}