0
votes

I'm creating an angular application and created 3 simple crud operations. I've used ngrx for state management and it works nicely. I've subscribed to some slices of the states of each crud like

createUserLoaded$.subscribe(loaded => this.showSuccessNotification());

All is working good. I'm subscribing to these observables on ngOnInit of the respective component and unsubscribing all of them again on ngOnDestroy.

But the problem is, when I create a user, go to another route and come back to the create user route back, it shows me the success notification. The reason is last state of createUserLoaded$ that was true and the respective component again subscribes to it.

So I wanted the opinion from the community that should I reset the reducer to its initial state again? Is it a good practice? or what else I should do?

1
if i read your question correctly...you should be using async pipe and forget about subscriptions to state. you pass your slices (which are observables) to your properties using async pipe and it does subscription management for you. - dee zg
No its not like that. I'm already using async. The thing I'm asking is, resetting the reducer to its initialState is a good idea or bad if I come back to the component from another route - Manish Jangir
aha, ok now i see... i setup that kind of things like this: i have CreateUserPending and CreateUserError flags in state. When http request for creating user starts i set CreateUserPending=true. When the respond comes back i set CreateUserPending=false and result: if error then CreateUserError=whateverErrorServerReturned or if 200 OK just set actual created user slice (or just redirect somewhere else, depends on your ux logic). When i enter component, i list users and set errors to null but that highly depends on your ux workflow how and when you show what messages. - dee zg

1 Answers

2
votes

Without code cant help you properly . but you can dispatch and event on ngOnDestroy() of your component to reset the state if you want to, also get in the habit of using async in your templates for your Observable they will do the unsubscribing for you. Ngrx goes hand and hand with the Smart/Dumb Component

 ngOnDestroy(): void {
    this.store.dispatch(new classAction.resetSuccessNotification());
 } 

If your just using toasts to show notifications and don't care for their state then you can just use effects for that.loggerService is just a service to show toast

@Effect({dispatch: false})
  createUserLoadede$ = this.actions$.pipe(
    ofType(Vendor.ActionType.CREATE_USER_LOADED),
    map((action: Vendor.createUserLoadedel) => action.payload),
    tap((payload) => this.loggerService.SuccessToast(payload.message, 6000))
  );