Home > Enterprise >  How to set a timer for an effect?
How to set a timer for an effect?

Time:08-31

I have an effect that gets the number of active notifications from the user. But I need to get updated information on the number of active notifications every 5 minutes. And for this I added a timer. But I am getting the following error:

Type argument "Observable<({ title: string; description: string; } & TypedAction<"[Toastr Notification] display error">) | ({ count: number; } & TypedAction<"[Notifications] load count notifications success"> )>" cannot be assigned to a parameter of type "OperatorFunction<unknown, unknown>". Type "Observable<({ title: string; description: string; } & TypedAction<"[Toastr Notification] display error">) | ({ count: number; } & TypedAction<"[Notifications] load count notifications success">) >" does not provide a match for signature "(source: Observable): Observable".

How can this be fixed?

  loadCountNotifications$ = createEffect(() => {
    return this.actions$.pipe(
      ofType(loadCountNotifications),
      timer(0, 300000).pipe(
        switchMap(() => {
          return this.notificationsService
            .count()
            .pipe(
              map((data) => {
                return loadCountNotificationsSuccess({ count: data });
              }),
              catchError((err) => {
                return of(
                  displayError({
                    title: `${err.error.statusCode} ${err.error.error}`,
                    description: err.error.message,
                  })
                );
              })
            );
        })
      )
    );
  });

CodePudding user response:

Use interval to poll for every 5 minutes.

loadCountNotifications$ = createEffect(() => {
    return this.actions$.pipe(
        ofType(loadCountNotifications),
        switchMap(() =>
            interval(300000).pipe(
                switchMap(() => {
                    return this.notificationsService.count().pipe(
                        map(data => {
                            return loadCountNotificationsSuccess({ count: data });
                        }),
                        catchError(err => {
                            return of(
                                displayError({
                                    title: `${err.error.statusCode} ${err.error.error}`,
                                    description: err.error.message,
                                })
                            );
                        })
                    );
                })
            )
        )
    );
});

CodePudding user response:

Maybe create the timer in another place in your app and just initiate a state change with it which in turn fires your effect again.

  • Related