Blog>
Snippets

Cancellation of an Async Thunk using AbortController

Provide an example of using an AbortController instance within a createAsyncThunk to cancel a request after a certain period or due to external conditions.
import { createAction, createAsyncThunk } from '@reduxjs/toolkit';

// Define an action to cancel the async thunk
export const cancelFetchUser = createAction('users/cancelFetch');

// Async thunk to fetch user data
export const fetchUser = createAsyncThunk(
    'users/fetch',
    async (userId, { signal }) => {
        // Make an HTTP request (fetch is just an example)
        const response = await fetch(`/api/users/${userId}`, { signal });
        const data = await response.json();
        return data;
    }
);

// Usage Example in a React component
// ... inside React component
const dispatch = useDispatch();

// Dispatch the fetch user thunk
const userFetch = dispatch(fetchUser(userId));

// Set a timeout to cancel the request after 5 seconds
const timeoutId = setTimeout(() => {
    userFetch.abort();
    dispatch(cancelFetchUser());
}, 5000);

// Cleanup on unmount or when conditions require cancellation
useEffect(() => {
    return () => {
        clearTimeout(timeoutId);
        if (!userFetch.signal.aborted) {
            userFetch.abort();
            dispatch(cancelFetchUser());
        }
    };
}, []);
This example shows how to use an AbortController to cancel an async thunk after a fixed timeout, or due to a component unmounting or other external conditions. It includes an action creator for canceling the fetch, and a createAsyncThunk that fetches user data and can be canceled with an AbortController signal. In the usage example within a React component, a timeout is used to automatically abort the fetch after 5 seconds. There is also cleanup logic to ensure we abort and dispatch the cancel action when the component unmounts or if the conditions change before the timeout.