platform icon indicating copy to clipboard operation
platform copied to clipboard

Docs: add docs on performing tasks based on dispatched actions within an active component

Open brandonroberts opened this issue 6 years ago • 4 comments

There is a common use case of wanting to perform some task inside a component based on actions that have been dispatched outside the component, normally with Effects. There are some common patterns to achieve this:

Use the Effects APIs to listen to dispatched actions:

import { Actions, ofType } from '@ngrx/effects';

@Component({ ... })
export class ActiveComponent {
  destroy$ = new Subject();

  constructor(private actions$: Actions) {}

  ngOnInit() {
    this.actions$.pipe(
      ofType(someSuccessAction),
      takeUntil(this.destroy$),
      tap(() => {
        this.doSomethingLocally();
      })
    ).subscribe();
  }

  ngOnDestroy() {
    this.destroy$.next();
  }

  doSomethingLocally() {
  }
}

Set some property in your state slice that gets updated, and listen for when that piece of state is updated.

import { Actions, ofType } from '@ngrx/effects';

@Component({ ... })
export class ActiveComponent {
  destroy$ = new Subject();
  done$ = this.store.select(selectDoneFromStateSlice);

  constructor(private store: Store<{}>) {}

  ngOnInit() {
    this.done$.pipe(
      filter(done => !!done),
      takeUntil(this.destroy$),
      tap(() => {
        this.doSomethingLocally();
      })
    ).subscribe();
  }

  ngOnDestroy() {
    this.destroy$.next();
  }

  doSomethingLocally() {
  }
}

We should document a recommended way to do this for developers.

brandonroberts avatar Nov 08 '19 20:11 brandonroberts

@brandonroberts Where should the documentation go?

jordanpowell88 avatar Nov 16 '19 18:11 jordanpowell88

Should this type of doc go under the Recipes section? As someone who has come from outside of the project when I first went to the docs and saw the Recipes section I was hoping to see some examples/docs on some common patterns I may need to follow when using NgRx.

This seems like a great example of what could go in this section of the docs.

Stephenradams avatar Nov 28 '19 09:11 Stephenradams

@jordanpowell88 @Stephenradams yep, that seems like a good place to me.

brandonroberts avatar Dec 03 '19 04:12 brandonroberts

This is exactly what I was looking for, thanks!

misaizdaleka avatar Mar 10 '20 22:03 misaizdaleka

Closing this one. This can be done with component store.

timdeschryver avatar Apr 15 '23 14:04 timdeschryver