NGXS - Handling of dispatching multiple actions
Solution 1:
You are catching the error in rxjs using catchError
, so it will never reach your try/catch
. Also the dispatch are async, so it will always show the showSnackbar
with the success message. This might work better.
Untested code, but maybe you'll understand the idea better
public save(): void {
this.store.dispatch([
new UploadAvatar(this.avatar),
new UpdateUser(this.user)
]).subscribe({
next: () => this.snackbar.showSnackbar('Changes were successfully saved'),
error: () => this.snackbar.showSnackbar('Changes could not be saved')
});
}
@Action(UploadAvatar)
public uploadAvatar(ctx: StateContext<AuthStateModel>, action: UploadAvatar) {
return this.uploadService.uploadAvatar(ctx.getState().token, action.avatar).pipe(
catchError((error: HttpErrorResponse) => {
ctx.patchState({ responseStatus: error.status });
return throwError(error);
})
);
}
@Action(UpdateUser)
public updateUser(ctx: StateContext<AuthStateModel>, action: UpdateUser) {
return this.userService.updateUser(ctx.getState().token, action.user).pipe(
catchError((error: HttpErrorResponse) => {
ctx.patchState({ responseStatus: error.status });
return throwError(error);
})
);
}
Basically, you catch the error in your state, write the response status to the state, and re-throw the same error, which can be caught with the dispatch