Blog>
Snippets

User-Initiated Retry Mechanism in Redux-Saga

Creating a Redux-Saga that listens for a user action to initiate a retry of the failed XHR call, adding user control over the retry process.
import { put, takeLatest, call } from 'redux-saga/effects';

// Action Types
const RETRY_ACTION = 'RETRY_ACTION';
const API_CALL_REQUEST = 'API_CALL_REQUEST';
const API_CALL_SUCCESS = 'API_CALL_SUCCESS';
const API_CALL_FAILURE = 'API_CALL_FAILURE';

// Worker saga: makes the api call when watcher saga sees the retry action
function* retryApiCallSaga() {
  try {
    const data = yield call(apiCall); // Replace apiCall with your api function
    yield put({ type: API_CALL_SUCCESS, data });
  } catch (error) {
    yield put({ type: API_CALL_FAILURE, error });
  }
}

// Watcher saga: spawns a new retryApiCallSaga on each RETRY_ACTION
function* watchRetryApiCall() {
  yield takeLatest(RETRY_ACTION, retryApiCallSaga);
}

export default watchRetryApiCall;
Defines a Redux-Saga watcher that listens for the RETRY_ACTION dispatched by the user, triggering the worker saga retryApiCallSaga to perform the API call. It demonstrates how to set up a basic retry mechanism in Redux-Saga, allowing user-initiated retries for failed API calls.
// Example dispatch action to trigger the retry
// This can be dispatched from your component in response to user action like button click

// Action creator for retrying the API call
const retryAction = () => ({
  type: 'RETRY_ACTION'
});
Shows how to define an action creator for the retry action. Dispatching this action (e.g., in response to a button click by the user) will trigger the saga to retry the API call.