Peter T.
Peter T.

Reputation: 3325

How to watch for changes of entities in a withEntities() ngrx signal store?

Scenario:

I use a signalStore(withEntities<Entity>() /*...*/).

I have a use case when I want to trigger some other updates whenever an entity in the store is added, updated or removed.

I'd like to use an effect() - but I miss an simple & elegant solution to find out about what changed since last call of the effect function.

I even don't get the previous store state (like in Vue's watch()) so I could compare myself.

Any suggestion?

Ideally, I'd like to have something like

watchEntities(store, (updated: EntityId[], added: EntityId[], removed: EntityId[]) => {
  // called as effect whenever things change in the store so I can
  // do whatever I need to keep other things in sync with these entities
};

AI suggested to do something like:

toObservable(store).pipe(
  startWith(null),
  pairwise()
).subscribe(([prev, current]) => {
  if (prev === null) return; // Skip initial emission
  // ...and an awful lot of code to detect the changes...

So I'd say it's simple to augment my modification methods to trigger the actions.

Upvotes: 1

Views: 402

Answers (1)

rainerhahnekamp
rainerhahnekamp

Reputation: 1136

Yes, you could use a Signal to emit whenever a new value is created. However, keep in mind that if multiple entities are created synchronously, the Signal will only emit the last value from that batch.

In your scenario, I’d suggest having one public method that exposes an Observable (to avoid dropping values) and a private method (prefix the method name with _) containing the Subject. Internally, you can use the Subject to emit values, while the exposed Observable is simply the Subject wrapped with asObservable.


With NgRx 19, you will have a withProps that allows you to add the Observable directly as property.


That said, the more important question is whether you actually need to do this. Since entities can only be updated, modified, or added within the SignalStore, you already have a central point of control. This allows you to trigger any post-processing directly.

If that approach is feasible for your use case, it would definitely be my preferred solution.

Upvotes: 1

Related Questions