Blog>
Snippets

Sequential Task Execution in Redux Saga

Illustrate how to execute tasks sequentially using the `yield` keyword in Redux Saga, ensuring one task completes before the next begins.
import { call, put } from 'redux-saga/effects';
Import necessary effects from redux-saga.
function* fetchUserData(userId) { /* implementation */ }
Define async function to fetch user data.
function* updateUserProfile(profileData) { /* implementation */ }
Define async function to update user profile.
function* sequentialTaskExecutionSaga(action) {
Start of the saga to execute tasks sequentially.
  try {
Try block to handle potential errors in saga execution.
    const userData = yield call(fetchUserData, action.userId);
Call fetchUserData with userId and wait for it to complete.
    yield put({ type: 'FETCH_SUCCESS', userData });
Dispatch an action indicating successful user data fetch.
    const updatedProfile = yield call(updateUserProfile, userData);
Call updateUserProfile with userData and wait for it to complete.
    yield put({ type: 'UPDATE_SUCCESS', updatedProfile });
Dispatch an action indicating successful profile update.
  } catch (error) {
Catch block for handling errors.
    yield put({ type: 'OPERATION_FAILED', error });
Dispatch an action indicating the operation failed.
  }
End of the try-catch block.
}
End of the sequentialTaskExecutionSaga.