SoFunction
Updated on 2025-04-14

Detailed explanation of how to use React Redux to implement asynchronous requests

Complete code

import { createSlice } from "@reduxjs/toolkit";
import axios from "axios"

const channelStore = createSlice({
    name: 'channel',
    initialState: {
        channelList: []
    },
    reducers: {
        setChannels (state, action){
             = 
        }
    }
})

const { setChannels } = 

const fetchChannelList = () => {
    return async(dispatch) => {
        const res = await ('/v1_0/channels')
        dispatch(setChannels())
    }
}

export { fetchChannelList }

const channelReducer = 

export default channelReducer

This code shows an example of an asynchronous request using Redux Toolkit and axios implementation, mainly used to get a list of channels from the API and store it in Redux's state. Here is a detailed explanation of the code:

1. Import dependencies

import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

createSlice:

Redux Toolkit provides tools to simplify the creation of Redux actions and reducers.

It will automatically generate corresponding actions and reducers to reduce boilerplate code.

axios:

HTTP client, used to send asynchronous requests (such as GET, POST, etc.).

This is used to obtain channel data from the specified API.

2. Define channelStore

const channelStore = createSlice({
    name: 'channel',
    initialState: {
        channelList: []
    },
    reducers: {
        setChannels (state, action){
             = 
        }
    }
});

Parameter explanation

  • name: module name, namespace() defined in Redux.
  • initialState: defines the initial state.
  • channelList: An empty array to store the channel list.

reducers:

  • Defines synchronized state update logic.
  • Each reducer function receives two parameters:

state: Current status.

action: Includes type and payload (data load).

setChannels function

Function: Update the status of channelList.

Logic: Assign the content of .

3. Extract the setChannels action

const { setChannels } = ;

Automatically generated setChannels action.

Can be used to trigger setChannels reducer, update channelList.

4. Define asynchronous operation fetchChannelList

const fetchChannelList = () => {
    return async(dispatch) => {
        const res = await ('/v1_0/channels');
        dispatch(setChannels());
    };
};

effect

Purpose: Get channel data from the API and store it in Redux state.

logic:

Define an action that returns an asynchronous function:

Receives dispatch parameter to trigger synchronization action.

Use Send a GET request to the specified URL.

Extract the return channel list in the data:

Call dispatch(setChannels(...)):

Passes the extracted list of channels to the setChannels action.

Trigger setChannels reducer to update the status of channelList.

Notice

This is a Redux asynchronous action (also known as Thunk).

dispatch is provided by Redux to trigger synchronous or asynchronous state updates.

5. Export and define channelReducer

const channelReducer = ;
export default channelReducer;

channelReducer:

  • Part of the Redux Store to handle status updates to the channel module.
  • The reducer function automatically generated by createSlice.

Export channelReducer:

Processing logic for registering as channel state in the Redux Store.

6. Export fetchChannelList

export { fetchChannelList };

Export the asynchronous function fetchChannelList for use in the component.

The component can trigger an asynchronous request and update the status through dispatch(fetchChannelList()).

7. Code workflow

Initialization status:

The initial state of Redux is:

{
  channelList: []
}

Trigger an asynchronous request:

The component calls dispatch(fetchChannelList()).

fetchChannelList asynchronous function:

Use axios to send requests to the API.

Extract the returned channel list.

Call dispatch(setChannels(...)) to update the status.

Update status:

After the setChannels action is triggered, channelReducer updates the status:

 = ;

Status synchronize to the component:

After the Redux status is updated, components connected to Redux will automatically re-render to display the latest data.

8. Applicable scenarios

Used to manage dynamic data fetched from the backend, for example:

  • Channel List
  • User Information
  • Product List

9. Extended suggestions

Error handling:

Add an error capture mechanism in fetchChannelList:

try {
    const res = await ('...');
    dispatch(setChannels());
} catch (error) {
    ("Failed to fetch channels:", error);
}

Code interpretation

Loading status:

Add isLoading and error statuses to represent the process and results of data loading.

test:

Write unit tests to verify the logic of setChannels and fetchChannelList.

Summarize

This code implements a complete state management process through Redux Toolkit and axios, including the logic of asynchronously getting a channel list and storing it in Redux. It is a modular, scalable example of Redux state management.

This is the end of this article about how to use React Redux to implement asynchronous requests. For more related React Redux asynchronous requests, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!