Reputation: 5289
Is it possible to make an ngrx/effect
to listen on the select
operation? such as:
this.store.select('reducer')
Any suggestions?
Upvotes: 0
Views: 2035
Reputation: 992
Effects can be driven by many kinds of Observables.
It's valid to have an effect using state like this:
updateEstimatedTimeToShip$ = createEffect(() =>
this.store.select(selectShippingAddress).pipe(
switchMap(shippingAddress => this.shippingService.getEstimatedTimeToShip(shippingAddress).pipe(
map(timeToShip => GetUpdatedEstimatedTimeToShipSuccessful({ timeToShip })
)
)
);
updateEstimatedTimeToShip$
would be useful where we have some form that a user enters their address, and we'd like to call a service that makes an HTTP call to get an updated estimated time to ship.
Note that we could have the change detection logic in an effect that reacts to the FormValueChanged
action... but what if more than one action affected the shipping address? Now we'd have to repeat the logic in many effects.
We could also have individual actions fire for the different fields in the form, but why do so when we can already do change detection from the data in the store?
Having components be responsible for dispatching "change detection"-type actions seems superfluous to me when selectors seem purpose-built for change detection.
Upvotes: 0
Reputation: 894
Effects aren't supposed to listen to the store. Effects listen for actions. The reason being that effects remove side effects caused by doing an action. One reason is that it prevents things like API calls from being spammed while time travel debugging. If an effect was triggered from the store it would fire while debugging.
Effects trigger off of actions and in turn trigger other actions. The reducer also triggers off of actions. A reducer and an effect can trigger off of the same action.
So what you should be doing is instead of triggering an action off of the state. Trigger it off of the same action that alters the state in the way that you want the effect to trigger.
Upvotes: 3