I'm trying to figure out how to solve my problem, but I didn't find good enough solution on the web.
I need to cancel checkAuth and logout tasks when action LoginActionType.REQUEST_SEND
is dispatched.
function* handleLoginFetch(userCredentialsAction: PayloadAction<LoginActionType, UserCredentials>) {
try {
const response: AxiosResponse<AuthResponse> = yield call($http.put, '/users/login', userCredentialsAction.payload);
if (response.status === HttpStatusCode.OK) {
yield put(login.success(response.data.user));
}
} catch (error) {
yield put(login.failure());
}
}
function* handleCheckAuthFetch() {
try {
const response: AxiosResponse<AuthResponse> = yield call($http.get, '/users/logged-user', {
params: { 'include': 'user_user_permissions' }
});
if (response.status === HttpStatusCode.OK) {
if (yield select(getUserLoggedIn)) {
yield put(login.success(response.data.user));
} else {
yield put(checkLocalAuth.success(response.data.user));
}
}
} catch (error) {
yield put(checkLocalAuth.failure());
}
}
function* handleLogoutFetch() {
try {
const response: AxiosResponse = yield call($http.put, '/users/logout');
if (response.status === HttpStatusCode.OK) {
yield put(logout.success());
}
} catch (error) {
yield put(logout.failure())
}
}
export default function* userSaga() {
yield takeLatest(LoginActionType.REQUEST_SEND, handleLoginFetch);
yield takeLatest(CheckLocalAuthActionType.REQUEST_SEND, handleCheckAuthFetch);
yield takeEvery(LogoutActionType.REQUEST_SEND, handleLogoutFetch);
}
You could:
takeLatest
does. The docs saysSo instead of writing
yield takeLatest(CheckLocalAuthActionType.REQUEST_SEND, handleCheckAuthFetch);
you can write a function that does the same(the
takeLatest
functionspawn
s a saga while my implementationfork
s the saga but don't worry about it at the moment)handleLogoutFetch
userSaga
toSo, now:
CheckLocalAuthActionType.REQUEST_SEND
action triggers thehandleCheckAuthFetch
as it did before my implementationLogoutActionType.REQUEST_SEND
action triggers thehandleLogoutFetch
as it did before my implementationLoginActionType.REQUEST_SEND
action cancels every runninghandleCheckAuthFetch
andhandleLogoutFetch
sagasThat's what I do in my projects, it's up to you to abstract them to a utility function, I care that you understand how it works and how to implement it
NoriSte's answer really helped me to understand how to solve my issue. I studied Saga documentation a little bit more and I ended up with this solution.