Migrating Redux Thunks to Redux Toolkit's createAsyncThunk
Show how to convert existing redux-thunk actions to use Redux Toolkit's createAsyncThunk, which simplifies async action creators.
// Redux Thunk action before migration
const fetchUserData = (userId) => async dispatch => {
dispatch({ type: 'users/fetchUserStart' });
try {
const response = await fetch(`https://api.example.com/users/${userId}`);
const data = await response.json();
dispatch({ type: 'users/fetchUserSuccess', payload: data });
} catch (error) {
dispatch({ type: 'users/fetchUserError', payload: error.message });
}
};
This is the original Redux Thunk action fetching user data from an API. It manually dispatches actions for the start of the fetch, the success case, and the error case.
// Redux Toolkit `createAsyncThunk` migration
import { createAsyncThunk } from '@reduxjs/toolkit';
export const fetchUserData = createAsyncThunk(
'users/fetchUserData',
async (userId, { rejectWithValue }) => {
try {
const response = await fetch(`https://api.example.com/users/${userId}`);
const data = await response.json();
return data;
} catch (error) {
return rejectWithValue(error.message);
}
}
);
This is the migrated action using Redux Toolkit's `createAsyncThunk`. It handles the async logic and automatically dispatches the actions for pending, fulfilled, and rejected states.