Blog>
Snippets

Using Race Effect alongside Throttle

Illustrate the use of the race effect in conjunction with throttle to manage competing tasks within a Redux-Saga.
import { race, call, put, throttle } from 'redux-saga/effects';
import { fetchCurrentWeather, fetchWeatherForecast } from './weatherApi';
import { WEATHER_REQUEST, WEATHER_SUCCESS, WEATHER_FAILURE } from './actionTypes';
This code snippet imports necessary effects from redux-saga and function from an example weather API module. It also imports action types used to handle requests and responses.
function* weatherSaga(action) {
  try {
    const { currentWeather, weatherForecast } = yield race({
      currentWeather: call(fetchCurrentWeather, action.payload),
      weatherForecast: call(fetchWeatherForecast, action.payload)
    });
    yield put({ type: WEATHER_SUCCESS, currentWeather, weatherForecast });
  } catch (error) {
    yield put({ type: WEATHER_FAILURE, error });
  }
}
Defines a saga that concurrently runs two fetching tasks using the race effect. The first task to complete (resolve or reject) cancels the other. On success, it dispatches a WEATHER_SUCCESS action with the weather data. On failure, it dispatches WEATHER_FAILURE.
function* watchWeatherRequests() {
  yield throttle(5000, WEATHER_REQUEST, weatherSaga);
}
This watcher saga limits the invocation of weatherSaga to once every 5 seconds for WEATHER_REQUEST actions using the throttle effect. This prevents overloading the API with requests.