Initializing the Root Saga with fork and spawn patterns
Showcase how to use `fork` and `spawn` to initialize child sagas within a Root Saga, highlighting the error handling differences.
import { all, fork, spawn } from 'redux-saga/effects';
function* rootSaga() {
yield all([
fork(childSagaWithFork), // Using fork
spawn(childSagaWithSpawn) // Using spawn
]);
}
This code snippet initializes the root saga by using both fork and spawn patterns to start child sagas. The `fork` model creates a linked task that gets cancelled if the parent (rootSaga) is cancelled. The `spawn` model creates a detached task which will not be cancelled if the parent is cancelled. This shows a basic setup for starting child sagas with different error handling strategies.
function* childSagaWithFork() {
// Child saga logic with fork
try {
// Perform actions
} catch (error) {
// Handle errors specific to this saga
}
}
Defines a child saga that will be started with `fork` from the rootSaga. Errors are handled within the child saga, and if the rootSaga is cancelled, this saga will also be cancelled.
function* childSagaWithSpawn() {
// Child saga logic with spawn
try {
// Perform actions
} catch (error) {
// Handle errors specific to this saga
}
}
Defines a child saga that will be started with `spawn` from the rootSaga. It has its own try-catch block for error handling. Since it's initiated using `spawn`, it runs independently of the rootSaga's lifecycle, meaning it won't be automatically cancelled if the rootSaga is cancelled.