How best to use Reactive State?

Viewed 115

I have a big component, I store all the information about the selected items and all the information in the store(ngrx). There are different types in this component and I can switch between them and change information about them(via inputs). And then, at the click of a save button, send all changes to the server.

What is the best way to put changed data in the store?

  • Send to the store during an onchange event (minus: a lot of dispatch)
  • Send when switching between types (minus: you need to somehow check the status of the type that has been changed right now before pressing the save button)
  • Or, in general, is it a bad practice to put elements that will change, and better store them to service?

And another question, is it correct to carry out calculations in a reducer. For example, I dispatch a list of elements in the store and I need to add a new element for the selected type. I can do this through the service, but then I need to pull out all the elements, the selected type and a few more parameters, and then perform actions and put the changed array back into the store. Or do all these actions in a reducer with known data. Or in general, is this the wrong architectural approach to keep this list in the store?

1 Answers

Without knowing the use case it's hard to give a correct answer to this question, because it all depends on the needs.

As a rule of thumb, if the state only affects the current component, the ngrx store is not the place to store its data. An example of this is a form, it's usually an overkill to sync the form with the state in the store. That being said, if you need rehydration on the form, it's a good use case to keep the form and the store in sync.

The minus of dispatching a lot of actions, isn't a "real" downside of it imho - the ngrx store (redux in general) is designed to handle a lot of incoming actions.

To answer the second question, yes that's were reducers are for imho - it's here where I expect some logic. See the redux docs for more info.

You can also put some "view logic" inside the selectors, like filtering, sorting, paginination, ...

Mike and Brandon gave a talk at ng-conf and they explain what should belong in state and what does not. The talk gives useful insights, Reducing the Boilerplate with NgRx

Related