Blog>
Snippets

Basic Saga with Retry Logic

A simple Redux-Saga watcher that retries an XHR call three times with a fixed delay before giving up, using `retry` effect.
import { call, put, retry } from 'redux-saga/effects';

// Define your action types
const FETCH_POSTS = 'FETCH_POSTS';
const FETCH_FAILED = 'FETCH_FAILED';
const FETCH_SUCCEEDED = 'FETCH_SUCCEEDED';

// Define the API call function
function fetchPostsApi() {
  return fetch('https://example.com/posts').then(response => {
    if (!response.ok) throw new Error('Failed to fetch');
    return response.json();
  });
}
This piece of code imports necessary effects from redux-saga and defines the fetchPostsApi function which throws an error if the fetch call doesn't succeed, simulating a failed API call.
// Worker saga with retry logic
function* fetchPosts() {
  try {
    // Using the retry effect to try fetching data up to 3 times, waiting 2 seconds between each try
    const data = yield retry(3, 2000, fetchPostsApi);
    yield put({ type: FETCH_SUCCEEDED, data });
  } catch (error) {
    yield put({ type: FETCH_FAILED, error });
  }
}
This is the worker saga that attempts to fetch the posts using the fetchPostsApi function. It uses the `retry` effect to make up to 3 attempts at fetching the data, waiting 2 seconds between each attempt. In case of failure, a FETCH_FAILED action is dispatched.
import { takeLatest } from 'redux-saga/effects';

// Watcher saga
function* watchFetchPosts() {
  yield takeLatest(FETCH_POSTS, fetchPosts);
}
This piece of code creates a watcher saga that listens for the FETCH_POSTS action and then runs the fetchPosts worker saga. It uses the `takeLatest` effect to ensure that if the action is dispatched multiple times quickly, it will only respond to the latest.
import { all } from 'redux-saga/effects';

// Root saga
export default function* rootSaga() {
  yield all([
    watchFetchPosts(),
  ]);
}
Finally, this code defines the root saga, which combines all the watcher sagas using the `all` effect. This is where you would include other sagas if your application had more.