Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel request in Axios Instance class

I'm working with Redux-(saga) and a polling function. I need to do a request every 1sec. I need to do a new request when I do not receive a response from the endpoint. In this case I think I need to cancel the previous request and do a new xhr attempt to the api endpoint.

All my request are done with the Axios client. I've a class where I separate all my api call's. I've tried multiple examples (see my code below). And then I call the cancelRequest function.

Could someone please help me into the right direction?

Looked into these issues and axios documentation, but non of those could help me :(

Cant cancel Axios post request via CancelToken https://redux-resource.js.org/recipes/canceling-requests

import { getCookie } from '......';

const CancelToken = Axios.CancelToken;
let cancel;

/**
 * Create a single axios client for the 
 * @type {AxiosInstance}
 */
const apiClient = apiUrl =>
  Axios.create({
    baseURL: apiUrl,
    cancelToken: new CancelToken(function executor(c) {
      // An executor function receives a cancel function as a parameter
      cancel = c;
    }),
  });

/**
 * The Api is initialised with a Axios client.
 */
class PinResetApi {
  constructor(client) {
    this.client = client;
  }

  /**
   * Reset pin controller
   */
  requestChangePin = () =>
    this.client(......url).request({
      method: 'GET',
      headers: {
        ...
      },
    });

  /**
   * Cancel reset pin API
   */
  cancelRequest = () => this.client.cancel();

  /**
   * Reset pin status controller
   * @param
   */
  requestChangePinStatus = transactionId =>
    this.client(.....url).request({
      method: 'GET',
      headers: {
        ...
      },

    });
}

const _api = new PinResetApi(apiClient);

export default _api;
export { PinResetApi };
like image 764
Michieltronaut Avatar asked Oct 28 '25 04:10

Michieltronaut


1 Answers

You are trying to add token when you create axios instance once but you need to create and update token every time you send the request. You can update you apiClient wrapper like this:

// ../services.js

const apiClient = baseURL => {
  const axiosInst = axios.create({
    baseURL,
  });

  axiosInst.defaults.headers.common['Content-Type'] = 'application/json';
  
  return (type = 'get') => {
    let call = null;
    return (url, data, config) => {
      if (call) {
        call.cancel('Only one request allowed!');
      }
      call = axios.CancelToken.source();
      const extConf = {
        cancelToken: call.token,
        ...config,
      };
      switch (type) {
        case 'request':
          return api[type](extConf);

        case 'get':
        case 'delete':
        case 'head':
          return api[type](url, extConf);

        default:
          return api[type](url, data, extConf);
      }
    };
  };
}

export const baseApi = apiClient('http://localhost:5000/api/')

And then use it like this:

class PinResetApi {
  constructor(client) {
    this.client = client('request');
  }

  /**
  * Reset pin controller
  */
  requestChangePin = () =>
    this.client({
      method: 'GET',
      headers: {
      ...
    }),
});
like image 198
Alexander Yamkov Avatar answered Oct 30 '25 17:10

Alexander Yamkov