I need to handle multiple asynchronous actions and ensure that a third action is only triggered after the first two have successfully completed. I have created three saga workers for this purpose:
export function* emailUpdateRequestSaga(action: IEmailUpdateRequest) {
const requestURL = '/updateEmail';
const requestData = {
userId: action.userId,
email: action.email
};
try {
const {data, status}: Pick<AxiosResponse, 'data' | 'status'> = yield call(
update,
requestURL,
requestData
);
yield put(emailUpdateSuccess({data, status}));
} catch (err) {
console.log('err', err);
yield put(emailUpdateFail(err));
}
}
The second worker handles sending an email:
export function* genericEmailRequestSaga(action: IGenericEmailRequest) {
const requestURL = '/sendEmail';
const requestOpt = {
headers: {},
body: {
email: action.email
}
};
try {
const {data, status}: Pick<AxiosResponse, 'data' | 'status'> = yield call(
post,
requestURL,
requestOpt
);
yield put(genericEmailSuccess({data, status}));
} catch (err) {
console.log('err', err);
yield put(genericEmailFail(err));
}
}
And finally, the third worker orchestrates both actions and triggers a success action only if both are successful:
export function* emailSendAndUpdateRequestSaga(action: IEmailSendAndUpdateRequest) {
try {
// Call the first worker
yield put(emailUpdateRequest(action.userId, action.email));
// Call the second worker
yield put(genericEmailRequest(action.email));
// Trigger success action only if both previous actions were successful
yield put(emailSendAndUpdateSuccess(true));
} catch (err) {
console.log('err', err);
yield put(emailSendAndUpdateFail(err));
}
}
This is the watcher function that connects all sagas:
export function* sagas() {
yield takeEvery(EmailActionEnum.SEND_EMAIL_REQUEST, genericEmailRequestSaga);
yield takeEvery(EmailActionEnum.EMAIL_UPDATE_REQUEST, emailUpdateRequestSaga);
yield takeEvery(EmailActionEnum.EMAIL_SEND_AND_UPDATE_REQUEST, emailSendAndUpdateRequestSaga);
}
The issue I am facing is that the success action in emailSendAndUpdateRequestSaga
is triggered even if the previous actions fail. How can I ensure that the third action is only triggered when both previous actions have succeeded?