Setting a Global Timeout for Async Thunks
Demonstrate how to set a global timeout across all async thunks to prevent long-running operations from hanging indefinitely.
import { createAsyncThunk } from '@reduxjs/toolkit';
// Set a global timeout value (in milliseconds)
const GLOBAL_TIMEOUT = 5000;
// Create an async thunk with a timeout
export const myAsyncThunk = createAsyncThunk(
'myFeature/myAsyncThunk',
async (arg, { rejectWithValue }) => {
// Create an AbortController instance
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), GLOBAL_TIMEOUT);
try {
// Make an async call with an abort signal
const response = await fetch('https://myapi.com/endpoint', {
signal: controller.signal
});
clearTimeout(timeoutId); // Clear the timeout if the fetch completes in time
return await response.json();
} catch (error) {
clearTimeout(timeoutId); // Ensure to clear the timeout in case of an error
if (error.name === 'AbortError') {
// Handle the timeout case
return rejectWithValue('Request timed out');
}
return rejectWithValue(error.message);
}
}
);
This code snippet shows how to create an async thunk using Redux Toolkit's createAsyncThunk with a global timeout. A global constant `GLOBAL_TIMEOUT` is set to define the timeout duration. An abort controller and associated timeout are set up for each async call. If the timeout is reached, the controller aborts the fetch operation, and the code handles the abortion as a 'Request timed out' error. In the absence of a timeout or other errors, the fetch completes, and the resulting data is returned.