Implementing Fixed Interval Retry Logic in Redux-Saga
Show how to implement a simple retry logic in Redux-Saga for API calls with a fixed time interval between attempts.
import { call, put, delay } from 'redux-saga/effects';
Imports the necessary functions from Redux-Saga.
function* fetchRetrySaga(action) {
const maxAttempts = 3;
let attempts = 0;
while (attempts < maxAttempts) {
try {
// Attempt the API call
const response = yield call(apiCall, action.payload);
// If successful, dispatch success action
yield put({ type: 'FETCH_SUCCESS', payload: response });
break; // Exit loop on success
} catch (error) {
// If an error occurs, increment the attempt counter
attempts++;
if (attempts >= maxAttempts) {
// If max attempts reached, dispatch failure action
yield put({ type: 'FETCH_FAILURE', payload: error });
} else {
// If not, wait for a fixed interval before retrying
yield delay(2000); // 2 seconds delay
}
}
}
}
Defines a saga that retries an API call up to a maximum number of attempts. It waits for a fixed interval of 2 seconds between each attempt. On success, it dispatches a success action; on failure (after max attempts), it dispatches a failure action.