Blog>
Snippets

Saga Effects for Handling Race Conditions

Illustrate the use of `race` effect in Redux-Saga to handle race conditions, such as cancelling ongoing API calls when a newer one is made or a certain action is dispatched.
import { race, take, call, put } from 'redux-saga/effects';

function* fetchResource(resource) {
  const { response, cancel } = yield race({
    response: call(api.fetchResource, resource),
    cancel: take('CANCEL_FETCH')
  });

  if (response)
    yield put({ type: 'FETCH_SUCCESS', response });
  else
    yield put({ type: 'FETCH_CANCELLED' });
}
This saga demonstrates using the `race` effect to handle a race condition between an API call and a cancellation action. The `race` effect waits for either the `response` from the API call to succeed or for a `CANCEL_FETCH` action to be dispatched. If the API call succeeds first, a success action is dispatched. If the cancellation action is dispatched first, it triggers a cancelled action instead. This enables efficient management of concurrent operations, such as cancelling ongoing fetch requests when a newer request is made or when a user navigates away.