Search code examples
angularrxjsngrxngrx-storengrx-effects

Leak memory in NGRX Effect


Im trying to create two effects, one that call the login endpoint and other for handle the loading, redirection and everything else.

But i have a memory leak in the second effect, i'm just doing a console log for test.

I prove differents operators like take(1), and take first.

auth.component.ts

 onSubmit(): void {

    const credentials = this.getCredentials();
    this.store.dispatch( authActions.LOGIN_START({payload: credentials}));

  }

auth.reducer.ts

export const authReducer = createReducer(
    initialState,
    on(LOGIN_START, (state, {payload}) => ({ ...state, username: payload.username, loading: true})),
    on(LOGIN_SUCCESS, (state)=> state)
)

auth.action.ts

export const LOGIN_START = createAction('[Auth Component] Login Start', props<{payload: UserAuth}>());

auth.effects.ts

loginStart$ = createEffect(() =>
    this.actions$.pipe(
      ofType(authActions.LOGIN_START),
      switchMap((action) =>{
        return this.authService.loginUser(action.payload).pipe(
          tap(() => console.log('I RUN')),
           ///TOKEN LOGIC
          map(() => ({
            type: '[Auth Component] Login Success'
          })),
          catchError(() => of({ type: '[Auth Component] Login Fail Error' }))
        )}
      )
    )
  );

  loginSucces$ = createEffect(() =>
    this.actions$.pipe(
      ofType(authActions.LOGIN_SUCCESS),
      tap(()=>{
        console.trace()
      })
    )
  );

When i dispatch the login action, this is the log out.

enter image description here


Solution

  • You either need to dispatch another Action or define the effect as not dispatching.

    Do:

    loginSucces$ = createEffect(
      () => this.actions$.pipe(
        ofType(authActions.LOGIN_SUCCESS),
        tap(() => console.trace()),
      ),
      { dispatch: false },
    );