乐闻世界logo
搜索文章和话题

How to use dispatch in createSlice reducer?

1个答案

1

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:

  1. Create an asynchronous thunk action: Utilize createAsyncThunk to define an asynchronous action.

  2. Within this asynchronous action, dispatch other actions: Inside this thunk action, you can dispatch any other synchronous or asynchronous actions.

  3. 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:

javascript
import { 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:

javascript
function 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.

2024年6月29日 12:07 回复

你的答案