Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

reactjs - Cancel Saga when multiple components use it

I've been trying to work this out, making some research and breaking my head, but I've still haven’t figured this out.

So I have a React + Redux application. At some point, the application renders multiple same components

return (
  <MyComponent id={1} path={path} />
  <MyComponent id={2} path={path} />
  <MyComponent id={3} path={path} />
)

Here, MyComponent is connected to redux and makes an API call using Saga. I tried to implement a mechanism to be able to cancel those API request with something like this:

export function* watchMyRequest(action) {
  const task = yield fork(getRequestSaga, action);
  yield take(RESET_REQUEST_DATA);
  yield cancel(task);
}

Each time path changes, I dispatch an action for RESET_REQUEST_DATA which should cancel my saga. The problem is that as I have multiple identical components, they will all call on the cancel action.

My question is, how can I manage just to call on an specific cancel using Sagas?

question from:https://stackoverflow.com/questions/65928541/cancel-saga-when-multiple-components-use-it

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you have the same action type, then you need to use other part of the action object to differentiate between the various instances. For example, in the React part of your example you give each component an id. You can include this id as part of the watch/reset actions and then use the take(fn) api to listen for particular id.

function* watchMyRequest(action) {
  const task = yield fork(getRequestSaga, action);
  yield take(a => a.type === RESET_REQUEST_DATA && a.id === action.id);
  yield cancel(task);
}

You can see it working here: https://codesandbox.io/s/gyhlg?file=/src/index.js


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...