Blog>
Snippets

Implementing a Basic Saga for Asynchronous User Login

Showcase a simple saga that handles user login by waiting for a login action, calling the authentication API, and then dispatching an action based on the success or failure of the API call.
import { call, put, takeLatest } from 'redux-saga/effects';
import { LOGIN_REQUEST, loginSuccess, loginFailure } from './actions';
import { authenticateUser } from './api';
Imports necessary functions from redux-saga, action creators, and the authentication API.
function* loginSaga(action) {
  try {
    const { username, password } = action.payload;
    // Call API for authentication
    const response = yield call(authenticateUser, username, password);
    // Dispatch success action with user data
    yield put(loginSuccess(response));
  } catch (error) {
    // Dispatch failure action with error message
    yield put(loginFailure(error.message));
  }
}
Defines the login saga, which waits for the LOGIN_REQUEST action, calls the API with the credentials, and dispatches either a success or failure action based on the API response.
function* watchLoginRequest() {
  // Start watching for LOGIN_REQUEST actions
  yield takeLatest(LOGIN_REQUEST, loginSaga);
}
Creates a watcher saga that listens for LOGIN_REQUEST actions and delegates them to the loginSaga for handling.
export default watchLoginRequest;
Exports the watcher saga to be included in the saga middleware.