Search code examples
angularrxjsngrx

NgRx - Action being dispatched multiple times when in ngOnInit


I have a project (using Angular and NgRx) in which there are two pages (two different routes) where I need data being fetched when the user goes to each page. To achieve that, there is a component that when initialized does the following:

code of ngOnInit funcion

The function retrieveTasks(date) dispatch the action that is causing problems.

When going to the page for the first time everything works correctly, but when going to another page and then going back to this page, the actions are being dispatched multiple times (and it adds up everytime you go back and forth to this page)

  • Actions when the component is first initialized:

first time component is initialized

  • Actions when the component is "re-initialized":

enter image description here

I'm new to Angular, to RxJS and NgRx and would like to know what am I doing wrong and what is the best approach to this.


Solution

  • The issue is you didn't unsubscribe from your selects (observables), so they are still live even though component is destroyed

    change to this

    export class component implement OnInit, OnDestroy  {
    
       private unsubscribeAll: Subject<any> = new Subject<Any>();
    
       ngOnInit() {
    
    
         this.store.select(selector)
         // add takeUntil on all selects or any other observables you subscribe
            .pipe(
               takeUnitl(this.unsuscribeAll)
            )
            .subscribe(...) //rest of your code for subscription
    
       }
    
       ngOnDestroy() {
          this.unsubscribeAll.next();
          this.unsubscribeAll.complete();
       }
    }