Blog>
Snippets

Creating a Basic Saga for Asynchronous Data Fetching

Demonstrate the process of creating a basic Saga function to handle an asynchronous API request using generator functions.
import { call, put, takeLatest } from 'redux-saga/effects';
import { fetchQuoteSuccess, fetchQuoteFailure } from './actions';
import { FETCH_QUOTE_REQUEST } from './actionTypes';
import { getQuoteFromAPI } from './api';

// Worker saga: will be fired on FETCH_QUOTE_REQUEST actions
function* fetchQuoteSaga() {
  try {
    // Call our getQuoteFromAPI function
    const quote = yield call(getQuoteFromAPI);
    // Dispatch a success action to the store with the new quote
    yield put(fetchQuoteSuccess(quote));
  } catch (error) {
    // Dispatch a failure action to the store with the error
    yield put(fetchQuoteFailure(error.message));
  }
}

// Watcher saga: spawns a new fetchQuoteSaga on each FETCH_QUOTE_REQUEST action
function* watchFetchQuote() {
  yield takeLatest(FETCH_QUOTE_REQUEST, fetchQuoteSaga);
}
This piece of code demonstrates how to set up a basic Redux Saga to handle an asynchronous API request for fetching a quote. The 'fetchQuoteSaga' is a worker saga that makes the API call and handles success or failure scenarios. The 'watchFetchQuote' saga listens for FETCH_QUOTE_REQUEST actions and triggers 'fetchQuoteSaga'.