Blog>
Snippets

Automated Retries with createAsyncThunk

Present a technique for implementing automatic retries in the event of a failure within a createAsyncThunk action.
import { createAsyncThunk } from '@reduxjs/toolkit';

// Helper function to retry an async operation a specified number of times
const retryAsync = async (asyncFunc, args, retries) => {
  try {
    return await asyncFunc(args);
  } catch (error) {
    if (retries === 1) throw error;
    return await retryAsync(asyncFunc, args, retries - 1);
  }
};

// createAsyncThunk with retry logic
export const fetchWithRetry = createAsyncThunk(
  'data/fetchWithRetry',
  async (arg, { rejectWithValue }) => {
    try {
      // The actual fetching function and the retry count
      return await retryAsync(fetchSomeData, arg, 3);
    } catch (error) {
      // Handle the final failed attempt
      return rejectWithValue(error.message);
    }
  }
);

// The function you'd like to retry upon failureasync function fetchSomeData(arg) {
  // Implementation of the fetching logic goes here
}
This code defines a helper function `retryAsync` which will attempt to run a given async function a specified number of times before throwing an error. The `fetchWithRetry` Thunk uses this helper function to retry fetching data up to 3 times upon failure before giving up and rejecting the value with an error message.