Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite loop with ngrx/effects

I'm trying to understand ngrx/effects. I have built a simple function that increments number by 1 with each click. But it's going in an infinite loop when clicked, not sure whats going on. I'm sure im making some stupid mistake.

monitor.effects.ts

@Injectable()
export class MonitorEffects {
    @Effect()
    compute$: Observable<Action> = this.actions$
        .ofType(monitor.ActionTypes.INCREMENT)
        .map((action: monitor.IncrementAction) => action.payload)
        .switchMap(payload => {
            return this.http.get('https://jsonplaceholder.typicode.com/users')
             .map(data => new monitor.IncrementAction(payload+1))
             .catch(err => of(new monitor.InitialAction(0)))
        });

    constructor(private actions$: Actions, private http:Http ) {};
}

monitor.component.ts

ngOnInit() {
    this.storeSubsciber = this
      .store
      .select('monitor')
      .subscribe((data: IMonitor.State) => {
        this.value = data.value;
        this.errorMsg = data.error;
        this.currentState = data.currentState;
      });
  }

  increment(value: number) {
    this.store.dispatch(new monitorActions.IncrementAction(value));
  }

monitor.reducer.ts

export const monitorReducer: ActionReducer<IMonitor.State> = (state = initialState, action: Actions) => {
  switch (action.type) {
    case ActionTypes.INCREMENT:
      return Object.assign({}, { value: action.payload, currentState: ActionTypes.INCREMENT, error: null });
...
...
...

    default:
      return Object.assign({}, { value: 0, currentState: ActionTypes.INITIAL, error: null });
  }
}
like image 321
Sudhakar Avatar asked Dec 02 '16 02:12

Sudhakar


1 Answers

I was having this issue and the answers here didn't help. For me, I had a "success" action that had a tap() to navigate. My browser would lock up and I didn't understand why until I put a log in my tap function and noticed it was getting hit infinitely.

My issue was that the effect was calling itself when tap returned the same observable. What I missed, and my solution... was putting dispatch: false on my effect to prevent it from dispatching itself.

@Effect({dispatch: false})
like image 140
Dallas Avatar answered Sep 17 '22 14:09

Dallas