Creating and Cancelling a Task in Redux-Saga
Show how to initiate a Saga task to perform an asynchronous data fetch and then demonstrate how to cancel the task if needed, using Redux-Saga's `yield fork()` to start the task and `yield cancel()` to stop it.
import { take, fork, cancel, call } from 'redux-saga/effects';
import { fetchData } from './api';
function* fetchTask(action) {
try {
const data = yield call(fetchData, action.payload);
// process the fetched data
} catch (error) {
// handle error
}
}
This piece defines a generator function fetchTask which tries to fetch data using fetchData function. It handles both success and failure scenarios.
function* watchFetchData() {
while (true) {
const action = yield take('FETCH_DATA_REQUEST');
const task = yield fork(fetchTask, action);
const action = yield take(['CANCEL_FETCH', 'FETCH_DATA_FAILURE']);
if (action.type === 'CANCEL_FETCH') {
yield cancel(task);
}
}
}
This saga watches for FETCH_DATA_REQUEST actions and forks a new fetchTask for each action. It also listens for CANCEL_FETCH or FETCH_DATA_FAILURE actions to cancel the ongoing fetch task.