Refactoring Thunks with createAsyncThunk
Convert an existing thunk to use the createAsyncThunk utility, showing how actions and states are automatically typed.
import { createAsyncThunk } from '@reduxjs/toolkit';
// Example thunk prior to refactoring
// function fetchUserById(userId) {
// return async dispatch => {
// const response = await userAPI.fetchById(userId);
// dispatch(userLoaded(response.data));
// };
// }
// Refactored thunk using createAsyncThunk
export const fetchUserById = createAsyncThunk(
'users/fetchByIdStatus',
async (userId, thunkAPI) => {
const response = await userAPI.fetchById(userId);
return response.data;
}
);
This refactored code defines an async thunk using createAsyncThunk to fetch a user by ID, replacing the manual thunk pattern. createAsyncThunk receives the action type string and a payload creator callback that performs the async operation. It automatically handles dispatching pending, fulfilled, and rejected action types.