Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 693
matthias Avatar asked Jun 25 '26 19:06

matthias


1 Answers

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.

like image 80
Mr. Gung Avatar answered Jun 30 '26 20:06

Mr. Gung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!