Redux Saga: How to use fork with examples...

ยท

2 min read

Redux Saga: How to use fork with examples...

In Redux Saga, the fork effect is used to create a new detached task that runs concurrently with the main saga. It allows you to run multiple sagas simultaneously, without blocking the execution of the parent saga.

Here's an example that demonstrates the usage of fork in Redux Saga:

import { take, put, fork } from 'redux-saga/effects';

// Worker Saga
function* workerSaga() {
  try {
    yield put({ type: 'LOADING_START' });

    const data = yield fetchDataFromAPI(); // Some asynchronous operation

    yield put({ type: 'FETCH_SUCCESS', payload: data });
    yield put({ type: 'LOADING_END' });
  } catch (error) {
    yield put({ type: 'FETCH_ERROR', payload: error });
    yield put({ type: 'LOADING_END' });
  }
}

// Parent Saga
function* mySaga() {
  while (yield take('FETCH_DATA')) {
    // Start a new detached task using fork
    yield fork(workerSaga);
  }
}

export default mySaga;

In this example, workerSaga is a separate saga that performs some asynchronous operations, such as fetching data from an API. The mySaga parent saga listens for the 'FETCH_DATA' action using take and starts a new detached task by forking the workerSaga using yield fork(workerSaga).

By using fork, the parent saga can continue listening for additional 'FETCH_DATA' actions and create new instances of the workerSaga concurrently without blocking the execution.

Detached tasks created using fork run independently, and any errors or results produced by the forked task are not propagated to the parent saga. This allows multiple instances of workerSaga to run concurrently without affecting each other.

Buy Me A Coffee

Did you find this article valuable?

Support Revive Coding by becoming a sponsor. Any amount is appreciated!

ย