I'm trying to implement a cancel task effect using redux-saga. It runs okay on the first dispatch but on the second time, it does nothing. It seems the saga has ended or something. Here's my code:
import { all, put, fork, take, cancel, cancelled } from "redux-saga/effects";
const searchUsers = function* () {
try {
yield new Promise((resolve) => setTimeout(resolve, 1500));
const users = ["Bill Gates"];
yield put({ type: "SEARCH_USERS_SUCCESS", users });
} catch (e) {
// log error
} finally {
if (yield cancelled()) {
console.log("search was cancelled");
}
}
};
const searchUsersSaga = function* () {
const searchAction = yield take("SEARCH_USERS");
const searchTask = yield fork(searchUsers, searchAction.query);
const cancleAction = yield take("SEARCH_USERS_CANCEL");
if (cancleAction.type === "SEARCH_USERS_CANCEL") {
yield cancel(searchTask);
}
};
const rootSaga = function* saga() {
yield all([searchUsersSaga].map(fork));
};
export default rootSaga;
I created a complete code here: https://codesandbox.io/s/new-fast-snhr0?file=/src/index.js