Blog>
Snippets

Basic race condition using Redux-Saga's race effect

Demonstrates how to set up a simple race condition between two asynchronous operations using the `race` effect in Redux-Saga, handling the winner and cancellation of the loser.
import { race, call, take, put } from 'redux-saga/effects';
import { fetchUserData, fetchDataTimeout } from './fetchServices';
import { CANCEL_FETCH, userDataSuccess, fetchFailed } from './actions';
Import required effects from redux-saga and necessary functions and actions from other modules.
function* watchFetchData() {
  while (true) {
    yield take('FETCH_USER_DATA_REQUEST');
    yield call(fetchDataWithTimeout);
  }
}
A saga that watches for 'FETCH_USER_DATA_REQUEST' action and then calls fetchDataWithTimeout saga.
function* fetchDataWithTimeout() {
  const { data, timeout } = yield race({
    data: call(fetchUserData),
    timeout: call(fetchDataTimeout, 5000)
  });
  if (data) {
    yield put(userDataSuccess(data));
  } else if (timeout) {
    yield put(fetchFailed('Timeout - Fetch operation canceled'));
    // Here you can also dispatch any necessary cleanup actions
  }
}
A saga to handle a race condition between fetching user data and a timeout. If user data returns first, the success action is dispatched. If the timeout occurs first, a failure action is dispatched.