Skip to content

createGenericAbortThunk

Generic thunk for async function with abort feature

Import

import { createGenericAbortThunk } from '@empeek-rnd-ui/redux/toolkit';

Usage

thunks.ts

const instance = axios.create({ baseURL });

const getUsers = (axiosConfig: AxiosRequestConfig = {}) => {
  return instance({
    method: 'GET',
    url: 'users',
    ...axiosConfig,
  });
};

export const fetchUsers = createGenericAbortThunk(
  'users/fetchUsers',
  async (params: undefined, axiosConfig) => {
    const response = await getUsers(axiosConfig);

    return response.data;
  },
);

//in your component
const fetchData = useCallback(() => {
  return dispatch(fetchAdmins());
}, [dispatch]);

useEffect(() => {
  const promises = [fetchData()];

  return () => {
    promises.forEach((promise) => {
      promise.abort();
    });
  };
}, [dispatch, fetchData]);

This thunk works like createGenericThunk, but with abort feature, so if your component unmount and request not finished your request will cancel.

canceled request