Blog>
Snippets

Basic Fork Example

Showcase how to create a simple attached fork in Redux-Saga using the `fork` effect, highlighting how the child saga remains attached to the parent saga.
import { fork, take, call, put } from 'redux-saga/effects';

function* watchFetchData() {
  // Watches for FETCH_DATA_REQUEST action to be dispatched
  yield take('FETCH_DATA_REQUEST');
  // Calls fetchDataSaga when the action is seen
  yield call(fetchDataSaga);
}

function* fetchDataSaga() {
  try {
    const data = yield call(fetchDataFromAPI);
    yield put({ type: 'FETCH_DATA_SUCCESS', data });
  } catch (error) {
    yield put({ type: 'FETCH_DATA_FAILURE', error });
  }
}
Defines a watcher saga (watchFetchData) that listens for a 'FETCH_DATA_REQUEST' action. Once this action is dispatched, it calls another saga (fetchDataSaga) to perform the actual data fetching logic. The fetchDataSaga saga attempts to fetch data from an API and dispatches a success or failure action based on the result. This showcases how to use the fork effect to start a task in the background in response to a specific action.
import { fork, all } from 'redux-saga/effects';

function* rootSaga() {
  yield all([
    fork(watchFetchData),
    // Add more watchers here
  ]);
}
Demonstrates how to use the `fork` effect within a root saga to start the watchFetchData saga in a non-blocking manner. This allows the application to continue running other sagas in parallel without waiting for watchFetchData to complete.