简体   繁体   中英

redux-saga injected twice

I have a redux-saga which is called once, but it is executing twice.

This is the action that starts the saga:

export function createRequest (data) {
  return {
    type: CREATE_REQUEST,
    payload: {data}
  };
}

and my sagas.js file looks this way:

export function* create (x) {
  try {
    const response = yield call(request, URL_TO_API, Object.assign({}, buildBaseHeaders('en'), {
      method: 'post',
      body: JSON.stringify(x.payload.data)
    }));
    yield put(createSuccess(response));
  } catch (error) {
    yield put(createFailure(error));
  }
}

... my other sagas

export default function* defaultSaga () {
  yield takeLatest(CREATE_REQUEST, create);
  ... my other calls
}

The way I'm injecting the sagas into my React component is this:

const withConnect = connect(mapStateToProps, mapDispatchToProps);
const withReducer = injectReducer({key: 'myComponent', reducer});
const withSaga = injectSaga({key: 'myComponent', saga});

export default compose(withReducer, withSaga, withConnect) MyComponent;

But the saga is injected twice. So, what am I missing here? How can I inject the saga only once no matter on how many times MyComponent gets rendered?

But the saga is injected twice. So, what am I missing here?

Solution is dependent on how redux-sagas-injector npm library works. In general case, asynchronous loading and applying for sagas is difficult thing, because saga is consists of "live" process manager, which can not be disposed on some function call or object deletion.
It implies from saga's ability to launch custom tick callback domains (Promises, AJAX/XHR, setImmediate , etc), which can not be disposed from custom external code (That's also reason, why HMR does not work with sagas in partial mode and should reload whole page).

So, if you perform saga injection on router switching, check two things: that old saga has implicit action to dispose from outer side, like special inner technical dispose action, and that there is not misconfiguration in router side - maybe same page had been launched, for example, twice.

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