调度特定操作时如何取消传奇任务 [英] How to cancel saga task when specific action is dispatched

查看:48
本文介绍了调度特定操作时如何取消传奇任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在想办法解决我的问题,但我没有在网上找到足够好的解决方案.

I'm trying to figure out how to solve my problem, but I didn't find good enough solution on the web.

当操作 LoginActionType.REQUEST_SEND 被调度时,我需要取消 checkAuth 和注销任务.

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);
}

推荐答案

NoriSte 的回答 真的帮助我理解了如何解决我的问题.我对 Saga 文档进行了更多研究,最终得到了这个解决方案.

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.

export default function* userSaga() {
    const checkAuthTask = yield takeLatest(CheckLocalAuthActionType.REQUEST_SEND, handleCheckAuthFetch);
    const logoutTask = yield takeEvery(LogoutActionType.REQUEST_SEND, handleLogoutFetch);

    yield takeLatest(LoginActionType.REQUEST_SEND, function*(userCredentialsAction: PayloadAction<LoginActionType, UserCredentials>) {
        if(checkAuthTask) yield cancel(checkAuthTask);
        if(logoutTask) yield cancel(logoutTask);

        yield fork(handleLoginFetch, userCredentialsAction);
    });
}

这篇关于调度特定操作时如何取消传奇任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆