Blog>
Snippets

Advanced Error Handling Strategies in Polling

Show an advanced example of managing errors during API polling by retrying the request with exponential backoff implemented within a createAsyncThunk's lifecycle.
// Import createAsyncThunk from @reduxjs/toolkit
import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

// Define initial exponential backoff parameters
const INITIAL_DELAY = 1000; // 1 second
const MAX_ATTEMPTS = 5;

// Create an async thunk for polling with exponential backoff error handling
export const fetchWithPolling = createAsyncThunk(
    'data/fetchWithPolling',
    async (arg, { rejectWithValue }) => {
        let attempts = 0;
        let delay = INITIAL_DELAY;

        while (attempts < MAX_ATTEMPTS) {
            try {
                // Replace with your API endpoint
                const response = await axios.get('/api/endpoint');
                // If request is successful, return the data
                return response.data;
            } catch (error) {
                attempts++;
                // If maximum attempts reached, reject with the error value
                if (attempts >= MAX_ATTEMPTS) {
                    return rejectWithValue(error);
                }
                // Wait for the delay period before retrying
                await new Promise(resolve => setTimeout(resolve, delay));
                // Exponentially increase the delay
                delay *= 2;
            }
        }
    }
);
This code snippet defines an async thunk using createAsyncThunk from Redux Toolkit, which performs polling on an API endpoint with exponential backoff in case of errors. It retries the request up to a specified maximum number of attempts, doubling the delay each time a retry occurs. If the maximum number of attempts is reached, the promise is rejected with the error value.