Blog>
Snippets

Handling AJAX requests with race effects

Shows how to use Redux-Saga's `race` effect to manage concurrent AJAX requests, where the first successful response is used, and the other requests are automatically cancelled.
import { race, call, put, take } from 'redux-saga/effects';
import { fetchDataSuccess, fetchDataFailure } from './actions';
import { fetchFirstData, fetchSecondData } from './api';
First, import necessary effects from redux-saga, actions for dispatching results, and the API functions for fetching data.
function* handleAjaxWithRace() {
  try {
    const { data, timeout } = yield race({
      data: call(fetchFirstData),
      timeout: delay(5000) // Example of timeout after 5s
    });

    if(data) {
      yield put(fetchDataSuccess(data));
    } else {
      yield put(fetchDataFailure('Timeout exceeded'));
    }
  } catch (error) {
    yield put(fetchDataFailure(error.message));
  }
}
Defines a generator function where a race condition is set between fetching data and a timeout. If the fetch completes first, dispatches success action with the data. In case of timeout or error, dispatches a failure action.
import { delay } from 'redux-saga';
Ensure to import the delay effect from redux-saga if you're using it for the timeout as shown in the example.