Home > Software engineering >  NGRX - Good practices advice
NGRX - Good practices advice

Time:01-07

is it okay to dispatch an action using the store instance inside an effect, or is it considered a bad practice ?

Another solution is instead of using the store instance, we just return the actions needed to be handled in the reducer.

which way is considered a best practice, used by developers ?

CodePudding user response:

As much as I hate ngrx (I know, I hide it well), from just a look at their lifecycle diagram, I would suggest that Actions are the key thing holding it all together and are what you should use.

Effects don't point to the store, components don't point to reducers, selectors don't point to services...

However, actions sit at the junction of the two sides of the diagram.

If you take a step back and think about what it is you want to do, even this sentence/question hints at it - it's what you want to do, what action do you want to take.

Actions are the key because those are what cause things to happen. If you wanted to shock someone, I'd pass you a taser - the taser performs the shocking action (for our purposes it's the action). The effect is the person is then shocked.

I can wrap it up further; I'm not physically with you, so my action is to package up the taser and send it to you (sending, verb, aka action). Your payload is the taser (action) that you can use to shock someone.

My action is to provide another action as a payload for you to use.

It's all actions. Give your targets the means to perform whatever actions they, in turn, want to perform, and hide away all of the complexity of stores and things.

Focus on what you want to do, hide away how you do it.

enter image description here

CodePudding user response:

In short: You should set up multiple on() statements in your reducer to listen for the same action dispatched from the effect if you want to trigger multiple state changes at once.

The point of using a more complex NGRX setup is to gain benefits in debugability from the output log of actions. If you start dispatching actions from within your effects, and then return some other action, you start to murky the waters.

I use selectors in my effects to get a slice of state if needed, but I like to reserve my action dispatching to be contained within the return block of the effect.

  • Related