Blog>
Snippets

Handling API Calls with Sagas

Demonstrate the use of `call` effect to make an API call, and `put` to dispatch an action with the result of the API call.
import { call, put } from 'redux-saga/effects';
import { fetchUserData } from './api'; // Import the API fetching function
import { GET_USER_SUCCESS, GET_USER_FAILURE } from './actionTypes';
This piece of code imports necessary functions and constants. The `call` and `put` effects from redux-saga, a hypothetical `fetchUserData` API call function, and action types for success and failure scenarios.
function* getUserSaga(action) {
  try {
    // Use the `call` effect to fetch user data
    const userData = yield call(fetchUserData, action.userId);
    // Use the `put` effect to dispatch a success action with the fetched data
    yield put({ type: GET_USER_SUCCESS, userData });
  } catch (error) {
    // Use the `put` effect to dispatch a failure action with the error
    yield put({ type: GET_USER_FAILURE, error });
  }
}
This generator function uses the `call` effect to make an API call. On success, it dispatches a success action with the recieved data. If an error occurs, it dispatches a failure action.