createAsyncThunk: abort previous request

I don’t know how your specific api works but below is a working example of how you can put the abort logic in the action and reducer, it will abort any previously active fake fetch when a newer fetch is made:

import * as React from 'react';
import ReactDOM from 'react-dom';
import {
  createStore,
  applyMiddleware,
  compose,
} from 'redux';
import {
  Provider,
  useDispatch,
  useSelector,
} from 'react-redux';
import {
  createAsyncThunk,
  createSlice,
} from '@reduxjs/toolkit';

const initialState = {
  entities: [],
};
// constant value to reject with if aborted
const ABORT = 'ABORT';
// fake signal constructor
function Signal() {
  this.listener = () => undefined;
  this.abort = function () {
    this.listener();
  };
}
const fakeFetch = (signal, result, time) =>
  new Promise((resolve, reject) => {
    const timer = setTimeout(() => resolve(result), time);
    signal.listener = () => {
      clearTimeout(timer);
      reject(ABORT);
    };
  });
// will abort previous active request if there is one
const latest = (fn) => {
  let previous = false;
  return (signal, result, time) => {
    if (previous) {
      previous.abort();
    }
    previous = signal;
    return fn(signal, result, time).finally(() => {
      //reset previous
      previous = false;
    });
  };
};
// fake fetch that will abort previous active is there is one
const latestFakeFetch = latest(fakeFetch);

const fetchUserById = createAsyncThunk(
  'users/fetchByIdStatus',
  async ({ id, time }) => {
    const response = await latestFakeFetch(
      new Signal(),
      id,
      time
    );
    return response;
  }
);
const usersSlice = createSlice({
  name: 'users',
  initialState: { entities: [], loading: 'idle' },
  reducers: {},
  extraReducers: {
    [fetchUserById.fulfilled]: (state, action) => {
      state.entities.push(action.payload);
    },
    [fetchUserById.rejected]: (state, action) => {
      if (action?.error?.message === ABORT) {
        //do nothing
      }
    },
  },
});

const reducer = usersSlice.reducer;
//creating store with redux dev tools
const composeEnhancers =
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
  reducer,
  initialState,
  composeEnhancers(
    applyMiddleware(
      ({ dispatch, getState }) => (next) => (action) =>
        typeof action === 'function'
          ? action(dispatch, getState)
          : next(action)
    )
  )
);
const App = () => {
  const dispatch = useDispatch();
  React.useEffect(() => {
    //this will be aborted as soon as the next request is made
    dispatch(
      fetchUserById({ id: 'will abort', time: 200 })
    );
    dispatch(fetchUserById({ id: 'ok', time: 100 }));
  }, [dispatch]);
  return 'hello';
};

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

If you only need to resolve a promise if it was the latest requested promise and no need to abort or cancel ongoing promises (ignore resolve if it wasn’t latest) then you can do the following:

const REPLACED_BY_NEWER = 'REPLACED_BY_NEWER';
const resolveLatest = (fn) => {
  const shared = {};
  return (...args) => {
    //set shared.current to a unique object reference
    const current = {};
    shared.current = current;
    fn(...args).then((resolve) => {
      //see if object reference has changed
      //  if so it was replaced by a newer one
      if (shared.current !== current) {
        return Promise.reject(REPLACED_BY_NEWER);
      }
      return resolve;
    });
  };
};

How it’s used is demonstrated in this answer

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top