In Redux's createSlice, using dispatch to trigger an action for another reducer is not directly possible because the reducer generated by createSlice is synchronous. However, you can leverage createAsyncThunk from Redux Toolkit or Redux middleware such as redux-thunk to address these needs.
Using createAsyncThunk
If you need to trigger another action after an action completes, you can proceed as follows:
-
Create an asynchronous thunk action: Utilize
createAsyncThunkto define an asynchronous action. -
Within this asynchronous action, dispatch other actions: Inside this thunk action, you can dispatch any other synchronous or asynchronous actions.
-
Handle these actions in
createSlice: You can process the results of these actions in the corresponding reducers.
Example Code
Suppose we have a user slice created with createSlice, and we want to update the user state after fetching user information:
javascriptimport { createSlice, createAsyncThunk } from '@reduxjs/toolkit'; // Async thunk action export const fetchUserById = createAsyncThunk( 'users/fetchById', async (userId, { dispatch, getState }) => { const response = await fetch(`https://api.example.com/users/${userId}`); const userData = await response.json(); // You can call other actions here dispatch(userActions.setUserDetails(userData)); return userData; } ); const userSlice = createSlice({ name: 'user', initialState: { entities: [], loading: 'idle', userDetails: null }, reducers: { setUserDetails(state, action) { state.userDetails = action.payload; }, }, extraReducers: (builder) => { builder.addCase(fetchUserById.fulfilled, (state, action) => { state.entities.push(action.payload); }); } }); export const { setUserDetails } = userSlice.actions; export default userSlice.reducer;
In this example, fetchUserById is an asynchronous thunk action where we fetch user data and use dispatch to call setUserDetails to update user details. Here, setUserDetails is a synchronous reducer that simply updates the Redux store state.
Using Middleware (such as redux-thunk)
If your project already integrates redux-thunk, you can also use dispatch within a thunk to call multiple actions:
javascriptfunction fetchUserAndUpdateDetails(userId) { return async function(dispatch, getState) { const response = await fetch(`https://api.example.com/users/${userId}`); const userData = await response.json(); dispatch(userActions.setUserDetails(userData)); } }
This approach does not rely on createAsyncThunk, but it still allows you to handle multiple operations within a single function, including API calls and dispatching actions.
These approaches are very useful for handling asynchronous logic and scenarios where you need to trigger other operations after an action completes. I hope this helps you understand how to use dispatch in Redux Toolkit.