Blog>
Snippets

Using `call` for Sequential API Requests

Demonstrate the use of `call` effect to handle dependent, sequential API requests where each request waits for the previous one to complete.
import { call, put } from 'redux-saga/effects';
function* getUserData(userId) {
  try {
    const user = yield call(fetchUser, userId);
    const profile = yield call(fetchUserProfile, user.id);
    const activities = yield call(fetchUserActivities, profile.id);
    yield put({ type: 'FETCH_SUCCESS', data: { user, profile, activities } });
  } catch (error) {
    yield put({ type: 'FETCH_FAILURE', error });
  }
}
This saga fetches user data in sequential order. First, it calls 'fetchUser' to get the user information. Once the user data is received, it proceeds to fetch the user's profile by calling 'fetchUserProfile'. After getting the profile, it fetches the user's activities with 'fetchUserActivities'. Each API call depends on the data retrieved from the previous call. If any request fails, an error action is dispatched.