Proper way to send UI notifications using NGXS

452 Views Asked by At

I'm new in NGXS and I try to figure out the right way to send UI toast notifications after success/error HTTP response using NGXS? Should we handle it in state:

  @Action(SomeRequestSuccess)
  public success(ctx: StateContext<SomeModel>, action: SomeRequestSuccess) {
    // like this
    this.store.dispatch([new SuccessToastNotification(msg)])
    // or just use service
    this.toastsService.showToast(action.payload.message, ToastsTypes.SUCCESS);
  }

or somehow keep error/success response in state and then use it in component:

@Select(selectors.someRequestSuccess) public success$: Observable<any>;

ngOnInit() {
  this.success$.subscribe(s => 
      this.toastsService.showToast(s.message, ToastsTypes.SUCCESS);
      this.reloadReport();
  );
}

// and same way for error
...

or any other way that you could suggest. Thanks in advance!

1

There are 1 best solutions below

0
On BEST ANSWER

Your first example, using a service, is my favorite approach for this kind of feature. Just remember that if this service returns a Subscribable or a Promise you can return the call to the showToast method to have the action lifecycle connected with the async operation.

Another approach is dispatching an action, also in your first example, and then grabbing this action using the ActionStream like shown below:

import { Injectable } from '@angular/core';
import { State, Actions, ofActionDispatched } from '@ngxs/store';

@State({...})
@Injectable()
export class MyState implements NgxsAfterBootstrap {
  constructor(action$: Actions) {}

  ngxsAfterBootstrap() {
    // synchronos
    action$.pipe(
      ofAction(SuccessToastNotification),
      tap(msg => this.toastsService.showToast(msg, ToastsTypes.SUCCESS))
    )

    // asynchronos
    action$.pipe(
      ofAction(SuccessToastNotification),
      mergeMap(msg => this.toastsService.showToast(msg, ToastsTypes.SUCCESS))
    )
  }
}

If you want more info about action handlers you can find in NGXS docs. The choice between these two approaches will depend on your team preferences and guidelines.