Blog>
Snippets

Creating a Worker Saga for Fetching Data

Demonstrate defining a worker saga that uses 'call' effect to fetch data from an API and 'put' to dispatch a success action with the fetched data.
import { call, put } from 'redux-saga/effects';
import { fetchDataSuccess, fetchDataFailure } from './actions';
import { fetchDataFromApi } from './api';
First, import the necessary effects from redux-saga and the action creators. Also, import fetchDataFromApi which simulates fetching data from an external API.
function* fetchUserData() {
  try {
    const data = yield call(fetchDataFromApi);
    yield put(fetchDataSuccess(data));
  } catch (error) {
    yield put(fetchDataFailure(error.message));
  }
}
Define a worker saga 'fetchUserData'. It tries to call 'fetchDataFromApi' using the 'call' effect. On success, it dispatches a success action with the fetched data using the 'put' effect. On failure, it dispatches a failure action with the error message.