Blog>
Snippets

Implementing a Retry Pattern in Redux-Saga

Provide an example of how to implement a retry pattern for a failed API call using a loop inside a Saga function.
import { call, put } from 'redux-saga/effects';

function* fetchResource(resource, params) {
  const maxRetries = 3;
  let retries = 0;
  while (retries < maxRetries) {
    try {
      const response = yield call(fetch, resource, params);
      // Assuming response.json() is the way our API gives us the successful result
      const data = yield response.json();
      yield put({ type: 'FETCH_SUCCEEDED', data });
      return; // Exit loop on success
    } catch (error) {
      if (retries === maxRetries - 1) {
        yield put({ type: 'FETCH_FAILED', error });
        return; // Exit loop after last retry
      }
      retries += 1;
      // Optionally, add some delay here with yield delay(ms)
    }
  }
}
This function fetchResource attempts to fetch data from an API and retries up to a maximum of 3 times upon failure before dispatching a FETCH_FAILED action. If the fetch is successful before reaching the maximum retries, it dispatches a FETCH_SUCCEEDED action with the obtained data.