Blog>
Snippets

Implementing a Basic Saga for Fetching Data

Demonstrate how to write a basic saga function that handles fetching data from an API endpoint, including using 'call' and 'put' effects to make the API call and dispatch actions based on the response.
import { call, put, takeEvery } from 'redux-saga/effects';
import Api from '...'; // Placeholder for actual API import
Imports necessary functions from redux-saga and a fictional Api module for making the actual API call.
function* fetchUserData(action) {
  try {
    const user = yield call(Api.fetchUser, action.userId);
    yield put({type: 'USER_FETCH_SUCCEEDED', user: user});
  } catch (e) {
    yield put({type: 'USER_FETCH_FAILED', message: e.message});
  }
}
Defines a generator function (saga) to fetch user data. It uses 'call' to make the API request and 'put' to dispatch actions based on the API call's success or failure.
function* mySaga() {
  yield takeEvery('USER_FETCH_REQUESTED', fetchUserData);
}
Defines the main Saga to listen for 'USER_FETCH_REQUESTED' actions and call fetchUserData saga in response.
export default mySaga;
Exports the main saga to be used in the application's middleware.