Vijay Ramesh
Vijay Ramesh

Reputation: 433

ngrx effects called multiple times after it return the value

ngrx effects called multiple times after it return the value.

loadMovies$: Observable<Action> = createEffect(() => {
    return this.actions$.pipe(
    ofType(counterActions.CounterActionTypes.IncrementCounter),
    flatMap(() => {
        return this.userService.counter()
        .pipe(
          map(movies => {
             return new counterActions.IncrementCounter();
          }));
      }
    ));
  });

Upvotes: 4

Views: 5084

Answers (4)

Shyam1319
Shyam1319

Reputation: 1

You directly use oprator distinctUntilKeyChanged("<key_name>")

loadMovies$: Observable<Action> = createEffect(() => {
    return this.actions$.pipe(
    ofType(counterActions.CounterActionTypes.IncrementCounter),
    distinctUntilKeyChanged("<key_name>"),
    flatMap(() => {
        return this.userService.counter()
        .pipe(
          map(movies => {
             return new counterActions.IncrementCounter();
          }));
      }
    ));
  });

Upvotes: 0

timdeschryver
timdeschryver

Reputation: 15507

It's not the first time I've seen this issue pop up, as it's an easy-to-make-and-overlook one.

That's why I added a rule for it in ngrx-tslint-rules to prevent it in the future.

Upvotes: 2

Triet Nguyen
Triet Nguyen

Reputation: 821

Because of createEffect function. You should remove wrapper createEffect function and just use this.actions$.pipe, instead. That will fix your issue. I already did and now it works okay.

loadMovies$ = this.actions$.pipe(
    ofType(counterActions.CounterActionTypes.IncrementCounter),
    flatMap(() => {
        return this.userService.counter()
          .pipe(
              map(movies => {
                  return new counterActions.IncrementCounter();
              })
          );
    })
);

Upvotes: -2

Tony
Tony

Reputation: 20092

You should add dispatch: false to your effect

  loadMovies$ = createEffect(() => {
    this.actions$.pipe(
    ofType(counterActions.CounterActionTypes.IncrementCounter),
    flatMap(() => {
        return this.userService.counter()
        .pipe(
          map(movies => {
             return new counterActions.IncrementCounter();
          }));
      }
    )),
    { dispatch: false };
  });

Example from document

  logActions$ = createEffect(() =>
    this.actions$.pipe(
      tap(action => console.log(action))
    ), { dispatch: false });

Upvotes: 5

Related Questions