简体   繁体   中英

Cancel some redux sagas when navigating

i'm facing a complicated issue here and your help will be highly appreciated. When, i'm navigating to the different pages of my application some services response with errors and i'm seeing that errors in the different pages. For example suppose i want to buy something and for this i call a saga that handles this task. Then i'm logging out immediately and i see an error in my login. When i change screen i want to cancel all the sagas expect from these that are running in the current page. For solving this i made an action which is dispatched when the user is changing from one screen to the other. This action is calling a generator function:

function* taskCancelHelper(actions, sagas) {
.....
}

My first question is how to "take" all actions expect from these that are dispatched in the current screen and call the appropriate sagas. I used:

const action = take(action => [..actions in the current screen].indexOf(action.type) < 0); but it does not seem to work.

Then i want to pass into an array all the sagas that are called when this actions are dispatch [the sagas of the above actions]. My thought is to pass those two array in my taskCancelHelper* generator function and use a for loop to cancel each task:

For (i=0; i < actions.length; i++) {
   yield cancel(sagas[i])
}

Do you know how to take all the actions expect from the current screen that call sagas?

In order to cancel sagas on LOCATION_CHANGE you can do the following:

 import { LOCATION_CHANGE } from 'react-router-redux';
 import { takeLatest, put, fork, take, cancel } from 'redux-saga/effects';
 import { FETCH_DATA } from './constants';

 export function* dataFetch(action) {
   try {
     // make an api call
   } catch(error) {
     console.log(error);
   }
 }

 export function* defaultSaga() {
   const loadDataWatcher = yield fork(takeLatest, FETCH_DATA, dataFetch);

   yield take(LOCATION_CHANGE);
   yield cancel(loadDataWatcher); // Will cancel your saga
 }

 export default defaultSaga;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM