Shortcut saga when to use a fork?

What is the difference between the two approaches below?

export function* watchLoginUser() { yield takeEvery(USER_LOGIN, loginUser) } export function* watchLogoutUser() { yield takeEvery(USER_LOGOUT, logoutUser) } export function* watchGetParties() { yield takeEvery(PARTIES_GET, getParties) } export default function* root() { yield [ fork(watchLoginUser), fork(watchLogoutUser), fork(watchGetParties) ] } 
 export default function* root() { yield [ takeEvery(USER_LOGIN, loginUser), takeEvery(USER_LOGOUT, logoutUser), takeEvery(PARTIES_GET, getParties) ] } 

When do I need to use fork, and when not?

+7
reactjs redux redux-saga
source share
1 answer

In general, fork is useful when a saga needs to run a non-blocking task. Non-blocking here means: the caller starts the task and continues execution, without waiting for completion.

There are many situations where this may be useful, but two main:

  • grouping sagas in a logical area
  • saving the link to the task in order to be able to cancel / join it.

The high-level saga may be an example of the first use case. You probably have something like:

 yield fork(authSaga); yield fork(myDomainSpecificSaga); // you could use here something like yield []; // but it wouldn't make any difference here 

Where authSaga is likely to include things like:

 yield takeEvery(USER_REQUESTED_LOGIN, authenticateUser); yield takeEvery(USER_REQUESTED_LOGOUT, logoutUser); 

You can see that this example is equivalent to what you suggested, calling the fork saga with a call to takeEvery . But in practice, you only need to do this for code organization purposes. takeEvery itself is a forked task, so in most cases this will be uselessly redundant.

An example of a second use case might be something like:

 yield take(USER_WAS_AUTHENTICATED); const task = yield fork(monitorUserProfileUpdates); yield take(USER_SIGNED_OUT); yield cancel(task); 

In this example, you can see that monitorUserProfileUpdates will be executed when the caller saga is renewed and will wait for the action USER_SIGNED_OUT to be sent. In addition, he can refer to it to cancel it if necessary.

For completeness, there is another way to start non-blocking calls: spawn . fork and spawn differ in how errors and undo bubbles from the child to the parent saga.

+18
source share

All Articles