In this article I will talk of my experience with NgRX, a reactive extension for Angular to manage state.
I've used NgRx on Ionic with Angular2 engine.
Ionic + NgRx
I've played the first time with NgRx on January 2018, inside a new project.
It took me a couple of days to enter in the idea of Actions, Reducers, Effects but, after these, it was immediately cool.
The concept is that components no longer invoke directly services; when they need new/fresh data they simply dispatch an action and nothing else.
The idea is delegation, like in our life.
Components don't want to know anything else apart of what type of action dispatch.
In this example, the component Films needs to retrieve the list of films. So, the only thing that he does is to dispatch the GET_FILM action and wait for data from the state.
Dispatching actions are the first things done in the NgRx state manager and are generally done by components.
The actions, eventually with a payload, will be taken from 2 others actors who do the job and update the state.
To go on, we need to know who are these 2 new actors...
I've the pleasure to introduce reducers and effects!
We need to start with the definition of side effects in NgRx: "side effects are non pure functions".
Pure functions are methods that, from the same inputs return ALWAYS the same output.
Examples of side effects are API calls.
Reducers are the responsables to save the output of effects in the NgRx state.
All the pure functions must stay in reducers. So, an incredible characteristic of reducers is that are easy to test.
While using NgRx, because of its power, you may be tempted to overuse it.
Like while cooking pasta, dispatch the action PUT_SALT in order to put salt in the water :D
(Yes, initially I've thinked it)
So, my advice is to think when is convenient to dispatch an action instead of put logic inside components.
Here you can find a full example of NgRx on Ionic2 -> https://github.com/texano00/ionic-ngrx-example