Blog>
Snippets

Automatically Retrying a Failed Operation in Redux Saga

Implement a saga that automatically retries an API call a specified number of times upon failure, using a loop and delay.
import { call, put, delay } from 'redux-saga/effects';
Imports call, put, and delay effects from redux-saga/effects.
function* fetchResource(resource) { 
  try { 
    const response = yield call(fetch, resource); 
    const data = yield response.json(); 
    yield put({type: 'FETCH_SUCCEEDED', payload: data}); 
  } catch (error) { 
    yield put({type: 'FETCH_FAILED', error: error.message}); 
  } 
}
Generator function that tries to fetch a resource and dispatches a success or failure action.
function* retrySaga(resource, maxRetries = 3, delayMs = 1000) { 
  for(let i = 0; i < maxRetries; i++) { 
    try { 
      yield call(fetchResource, resource); 
      break; // If succeed, exit loop 
    } catch(error) { 
      if(i < maxRetries - 1) { 
        yield delay(delayMs); // Wait for delayMs milliseconds before retrying 
      } else { 
        yield put({type: 'RETRY_LIMIT_REACHED', error: error.message}); 
      } 
    } 
  } 
}
Saga that retries fetching a resource up to maxRetries times, with a delay between each attempt. Dispatches a 'RETRY_LIMIT_REACHED' action if all attempts fail.