Blog>
Snippets

Combining race with other effects for complex workflows

Provides an example of how to combine Redux-Saga's `race` effect with other effects like `call` and `put`, to handle more complex, real-world application scenarios efficiently.
import { call, put, race, take } from 'redux-saga/effects';
import { fetchUserData, userTimeout } from './actions';

function* fetchUserSaga() {
  try {
    const { data, timeout } = yield race({
      data: call(fetchUserData),
      timeout: call(userTimeout, 3000)
    });

    if (data) {
      // Handle the successful fetch of user data
      yield put({ type: 'FETCH_SUCCESS', data });
    } else if (timeout) {
      // Handle the timeout case
      yield put({ type: 'FETCH_TIMEOUT' });
    }
  } catch (error) {
    // Handle any errors
    yield put({ type: 'FETCH_FAILURE', error });
  }
}
This code demonstrates combining the race effect with call and put to manage a scenario where a fetch request for user data competes against a timeout. If the fetch request completes first, the resulting data is handled as a success. If the timeout finishes first, a timeout action is dispatched. In either case, the race is handled gracefully, and errors are caught and managed.