Blog>
Snippets

Action-specific Timeout Configuration

Showcase code to configure a timeout specifically for a particular async thunk action, overriding any global timeout settings.
import { createAsyncThunk } from '@reduxjs/toolkit';

// A custom timeout function that will reject the promise after a specified time
const timeout = (ms) => new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), ms));

// Async thunk action with an action-specific timeout
export const fetchDataWithTimeout = createAsyncThunk(
    'data/fetchWithTimeout',
    async (arg, { rejectWithValue }) => {
        try {
            // Set your action-specific timeout duration here
            const actionTimeoutMs = 5000;

            // Promise.race will resolve or reject with whichever promise completes first
            const response = await Promise.race([
                fetch('/api/data'), // Replace with your actual API call
                timeout(actionTimeoutMs)
            ]);

            if (!response.ok) {
                throw new Error('Network response was not ok.');
            }

            return await response.json();
        } catch (error) {
            // Use rejectWithValue to return a custom payload from the rejected action
            return rejectWithValue(error.message);
        }
    }
);
This JavaScript snippet defines an async thunk action using Redux Toolkit's createAsyncThunk. The action, named 'fetchDataWithTimeout', attempts to fetch data from an API endpoint but includes an additional timeout mechanism. An action-specific timeout is set using the custom timeout function, which will reject the promise if the timeout duration is exceeded. The fetch request and timeout are used within Promise.race to ensure the request will either complete or timeout after a specified number of milliseconds, defined by the actionTimeoutMs variable. If the fetch fails or the timeout is reached first, the thunk action is rejected with a processed error using rejectWithValue.