Blog>
Snippets

Implementing timeout for an asynchronous task using race

Illustrates how to implement a timeout for an asynchronous operation using Redux-Saga's `race` effect, by racing the operation against a timed delay, and handling operation success or timeout.
import { call, race, put, delay } from 'redux-saga/effects';
import { fetchUserData } from './services/api';
import { userDataSuccess, userDataTimeout } from './actions';

function* fetchUserDataWithTimeout() {
  // Starts a race between the API call and a delay of 1 second
  const { data, timeout } = yield race({
    data: call(fetchUserData),
    timeout: delay(1000)
  });

  if (data) {
    // If the API call finishes first, dispatch success
    yield put(userDataSuccess(data));
  } else if (timeout) {
    // If the delay finishes first, dispatch timeout action
    yield put(userDataTimeout());
  }
}
This code snippet demonstrates how to use Redux-Saga's `race` effect to implement a timeout for an asynchronous task. In this case, it races an API call to fetch user data against a 1-second delay. If the API call resolves first, a success action is dispatched with the data. If the delay resolves first, indicating a timeout, a timeout action is dispatched instead. This pattern is useful for handling scenarios where an asynchronous operation might take too long and you want to fail gracefully.