Blog>
Snippets

Handling race conditions with the race effect

Example of using the race effect in Redux-Saga to manage race conditions, ensuring that only the first completed task has an effect.
import { race, take, put, call } from 'redux-saga/effects';
import { fetchUserData, fetchUserDataSuccess, fetchUserDataFailure, cancelFetch } from './actions';

function* fetchUserDataSaga() {
  try {
    // Initiating the race between fetching user data and cancel action
    const { data, cancel } = yield race({
      data: call(fetchUserData),
      cancel: take(cancelFetch)
    });

    // If the fetchUserData call completes before a cancel action is dispatched
    if (data) {
      yield put(fetchUserDataSuccess(data));
    }
    // If the cancel action is dispatched before the fetchUserData call completes
    if (cancel) {
      // Handle cancellation logic here, e.g., abort web request
    }
  } catch (error) {
    yield put(fetchUserDataFailure(error));
  }
}
This code demonstrates handling a race condition between a data fetch operation and a cancellation action using Redux-Saga's race effect. The first completion between the 'data' fetching operation and a 'cancel' action determines the code execution path. If fetching completes first, success action is dispatched. If cancel action completes first, it can trigger cancellation logic.