Blog>
Snippets

Implementing Non-blocking Data Fetch with `fork`

Showcase how to perform a non-blocking data fetch operation using `fork` effect in Redux Saga, enabling simultaneous operations.
import { fork, take, call, put, cancel } from 'redux-saga/effects';
import { fetchData } from './api';

// Worker saga to perform the data fetch
function* fetchResource(resource) {
  try {
    const data = yield call(fetchData, resource);
    yield put({type: 'FETCH_SUCCESS', data});
  } catch (error) {
    yield put({type: 'FETCH_FAILED', error});
  }
}
Defines a worker saga `fetchResource` that uses the effect `call` to perform the API call and dispatch actions based on the result.
function* watchFetchResource() {
  while (true) {
    const { resource } = yield take('FETCH_REQUEST');
    // Using fork for a non-blocking call
    const task = yield fork(fetchResource, resource);
    // Optionally, cancel the task if needed (e.g., user navigates away)
    // yield take('CANCEL_FETCH');
    // yield cancel(task);
  }
}
Implements a watcher saga `watchFetchResource` that listens for `FETCH_REQUEST` actions. It uses `fork` to start the `fetchResource` worker saga in a non-blocking manner, allowing for multiple fetches to occur in parallel.
export default function* rootSaga() {
  yield fork(watchFetchResource);
}
Root saga that starts the whole saga process, including the watcher saga `watchFetchResource`, using `fork` to ensure non-blocking execution.