Blog>
Snippets

Simulating Network Delays and Timeout Handling

A code snippet to simulate network delays in an API request and utilising createAsyncThunk's error handling to manage timeouts.
import { createAsyncThunk } from '@reduxjs/toolkit';

// Simulate a network delay using a timeout and then return some data
const simulateNetworkDelay = (milliseconds, data) => 
  new Promise(resolve => setTimeout(() => resolve(data), milliseconds));

// An example API call that resolves after a delay
const fetchUserData = (userId) => simulateNetworkDelay(2000, {user: 'John Doe'});
This snippet defines a function to simulate a network delay, using JavaScript's setTimeout function to resolve a promise after a specified number of milliseconds, and returns some dummy data.
const fetchUserWithTimeout = createAsyncThunk(
  'user/fetchWithTimeout',
  async (userId, { rejectWithValue, signal }) => {
    const abortController = new AbortController();
    const timeoutId = setTimeout(() => abortController.abort(), 5000);

    try {
      signal.addEventListener('abort', () => {
        throw new Error('Request canceled due to timeout');
      });

      const response = await fetchUserData(userId);
      clearTimeout(timeoutId);
      return response;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);
This snippet creates an async thunk action that wraps the API call with timeout logic. It sets up an abort controller to abort the fetch request if it takes longer than 5 seconds, using a JavaScript timeout. If the request is aborted or an error is thrown, the error is caught and returned using rejectWithValue, providing better error handling.