Search code examples
ngrx-storecomponent-store

ngrx/component-store trigger effect when state changes


I have an angular app with @ngrx/component-store.

when the user selects an entry from a list of devices, I store this into component-store

  component.ts:
  onDeviceClicked(device: DeviceTO) {
    this.inspectionStore.setDeviceSelected(device);
  }

  inspectionStore.ts
  readonly setDeviceSelected = (data: DeviceTO) =>  {this.patchState({selectedDevice: data})};

Now, that the user has selected a device, a side effect should be triggered. However I am not sure how I can trigger a side effect when part of the state changed.

Do I need to do it when updating state?

  readonly setDeviceSelected = (data: DeviceTO) =>  {
    this.patchState({selectedDevice: data});
    this.tiggerMySideEffect(data);
  };

Or is there another way I can tell the sideEffect to listen for changes?


Solution

  • Since an effect is automatically subscribed to, one does not need an external trigger (by calling the effect explicitly). The effect can directly react to the state-change. So the following (as an example) does work:

    public readonly selectedDevice$ = this.select(({ selectedDevice }) => selectedDevice);
    
    private readonly effectOnSelectedDevice = this.effect(_ => this.selectedDevice$.pipe(switchMap(selectedDevice => this.service.doSideEffect(selectedDevice))));
    

    Any observable can be used here (e.g. this.store or a combination with combineLatest, etc).

    To go a step further, you could have a chain of effects (hidden from the outside) - that react on state-changes performed by a previous effect to refine data (doing different calls to backends).

    None of them would need an explicit, manual trigger.