Blog>
Snippets

Utilizing the Enhanced createAsyncThunk API

Demonstrate how `createAsyncThunk` now supports cancellation and aborting for better async action management in RTK 2.0.
import { createAction } from '@reduxjs/toolkit';

// Define a cancellation action
export const cancelFetchingUser = createAction('users/cancelFetchingUser');
Define a cancellation action using createAction to be dispatched when the async task should be aborted.
import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

// Create an async thunk with cancellation support
export const fetchUserById = createAsyncThunk(
  'users/fetchById',
  async (userId, { signal }) => {
    const source = axios.CancelToken.source();
    signal.addEventListener('abort', () => {
      source.cancel();
    });
    
    const response = await axios.get(`/api/users/${userId}`, {
      cancelToken: source.token
    });
    return response.data;
  }
);
Create an async thunk using createAsyncThunk with enhanced API that includes the abort signal argument. Add event listener to abort the axios request when the thunk is aborted.
import { configureStore } from '@reduxjs/toolkit';

// Create a Redux store with the reducer that handles the async action and the cancellation action
const store = configureStore({
  reducer: {
    // reducers here
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      thunk: {
        extraArgument: {
          // You can pass extra arguments to your async thunks here
        }
      }
    })
});
Create a Redux store with a reducer and apply the default middleware with configuration that can handle the async thunk and the cancellation action.