reduxjs / redux-thunk

Thunk middleware for Redux
MIT License
17.77k stars 1.04k forks source link

Can I abort redux thunk dispatches? Without Redux toolkit or aborting the fetch request itself. #343

Closed Codex101 closed 1 year ago

Codex101 commented 1 year ago

Question

Is it possible to abort a dispatched redux thunk dispatch with just redux and redux thunk, no redux toolkit.

createAsyncThunk in Redux toolkit has a .abort function.

 return Object.assign(promise, { abort, requestId, arg }) 

Which can abort the dispatch like so

const promise = dispatch(
      asnycThunkCall({
        productId: "id",
      }),
    );

promise.abort();

Most examples using base redux and redux thunk seem to be aborting by passing in a signal to the fetch. However, I'm iteratively calling a fetch call. Like getBooks pages 1 - 10 in a promise.all, so it's not possible to pass in an abort signal to the fetch API call itself.

const fetchAction = createAsyncThunk(
  'fetchAction',
  async (_, { signal, requestId, dispatch }) => {
    console.log('Calling #' + requestId);
    signal.addEventListener('abort', () => {
      console.log('Aborted #' + requestId);
      dispatch({ type: 'abort', requestId });
    });
    const response = await fetch('some/path/to/file.json', { signal });

    return JSON.parse(await response.text());
  }
);

Can vanilla redux + redux thunk abort a dispatch? Or is the only real solution to use redux tookit, or another side-effect manager?

markerikson commented 1 year ago

No. A thunk is just a function, and there's no way to stop that by itself.

RTK's createAsyncThunk specifically works by making use of an AbortSignal inside.