Blog>
Snippets

Creating a Saga to Fetch User Data

Provide an example of a saga that listens for a 'FETCH_USER_REQUEST' action and uses 'call' effect to fetch user data from an API.
import { takeLatest, call, put } from 'redux-saga/effects';
import axios from 'axios';

// Action Types
const FETCH_USER_REQUEST = 'FETCH_USER_REQUEST';
const FETCH_USER_SUCCESS = 'FETCH_USER_SUCCESS';
const FETCH_USER_FAILURE = 'FETCH_USER_FAILURE';
Imports necessary utilities from redux-saga and axios for making API calls. Declares action types for requesting user data, and handling success and failure.
function* fetchUserData() {
  try {
    // Call the API
    const response = yield call(axios.get, 'https://jsonplaceholder.typicode.com/users');
    // Dispatch a success action to the store with the new data
    yield put({ type: FETCH_USER_SUCCESS, users: response.data });
  } catch (error) {
    // Dispatch a failure action to the store with the error
    yield put({ type: FETCH_USER_FAILURE, error });
  }
}
Defines the fetchUserData generator function. This function uses the call effect to make the API request and then dispatches either a success or failure action to the Redux store.
function* watchFetchUserData() {
  // Starts fetchUserData on each dispatched `FETCH_USER_REQUEST` action.
  // Allows concurrent fetches of user data.
  yield takeLatest(FETCH_USER_REQUEST, fetchUserData);
}
Defines a watcher saga that triggers fetchUserData whenever the FETCH_USER_REQUEST action is dispatched. Using takeLatest to ensure that it handles the result of the latest action dispatched if multiple requests are made.
export default watchFetchUserData;
Exports the watcher saga for integration into the main saga middleware. This will make sure our saga is running and listening for actions.