Blog>
Snippets

Dynamic Saga Injection and Cancellation

Demonstrate dynamically starting a saga when an action is dispatched and automatically cancelling it when it's no longer needed or when certain conditions are met.
import { fork, take, cancel, call } from 'redux-saga/effects';

function* dynamicSaga() {
  // Define your dynamic saga logic here
}

function* watchAndStart() {
  while (true) {
    const action = yield take('START_DYNAMIC_SAGA');
    // When START_DYNAMIC_SAGA action is dispatched, fork a new instance of dynamicSaga
    const sagaTask = yield fork(dynamicSaga, action.payload);
    // Wait for the cancellation action
    yield take('STOP_DYNAMIC_SAGA');
    // When STOP_DYNAMIC_SAGA action is dispatched, cancel the running saga
    yield cancel(sagaTask);
  }
}
This code demonstrates dynamic injection and cancellation of a saga in response to Redux actions. The 'watchAndStart' generator function waits for a 'START_DYNAMIC_SAGA' action to fork a new instance of the 'dynamicSaga'. It then pauses and waits for a 'STOP_DYNAMIC_SAGA' action, upon which it cancels the forked saga.
import { put } from 'redux-saga/effects';

function* dynamicSaga(payload) {
  try {
    // Perform the dynamic saga work here using the payload
    // For example, an API call with the provided payload
    // const data = yield call(apiFunction, payload);
    // On success, dispatch another action
    // yield put({type: 'DYNAMIC_SAGA_SUCCESS', data});
  } catch (error) {
    // On failure, dispatch a failure action
    yield put({type: 'DYNAMIC_SAGA_FAILURE', error});
  }
}
This snippet inside 'dynamicSaga' shows a generic structure for performing asynchronous work and handling success or failure. Insert your own saga logic and API calls where indicated. It's forked and potentially canceled by the watchAndStart saga.