Blog>
Snippets

Implementing Throttling with createAsyncThunk

Provide a code example of using createAsyncThunk along with throttling to manage the rate of dispatched actions from a high-frequency streaming source.
import { createAsyncThunk } from '@reduxjs/toolkit';
import { debounce } from 'lodash';

// Define a function with the async logic for the thunk,
// debounced to make sure it only runs at most once every second.
const debouncedAPIRequest = debounce(async (arg, thunkAPI) => {
    // Your API request logic here
}, 1000);

/* createAsyncThunk with a preparatory action creator that
 * calls the debounced function.
 */
export const fetchResource = createAsyncThunk(
    'resource/fetch',
    async (arg, thunkAPI) => {
        // The debounced request is triggered here,
        // but will only execute once within the debounce timeframe.
        return debouncedAPIRequest(arg, thunkAPI).then(
            response => response,
            error => thunkAPI.rejectWithValue(error)
        );
    }
);
This code creates a debounced API request function to manage the rate of dispatched actions from a high-frequency streaming source using lodash's debounce method. The fetchResource thunk action is defined using createAsyncThunk, which calls the debounced function, ensuring the API requests do not exceed the rate of one request per second.