Ionic @ In3
State Management with NgRx
March 13 / March 27
What is NgRx?
It's a state management framework based on Redux.
core components of ngrx
- actions
- reducers
- store
store
The store is the client-side database. At any given point in time, the store should represent the entire application state.
image courtesy of Brian Trocone
Actions
An action is a user interaction that would trigger an update in the application's state.
Examples of actions:
- user clicks on a button
- HTTP request finishes
- a timed event executes (setInterval)
Reducers
A reducer is a pure function that's used to update and retrieve a portion of the application state.
A reducer accepts two arguments:
- the current state
- Action (event type and event data)
With these two pieces of data, a reducer can make changes to the application state.
ngrx overview
When the user interacts with your app, (s)he can cause actions to be dispatched. These dispatched actions, which hold the user input and the current state, can execute reducers. The reducers then update the store, which in turn triggers UI updates in your app.
Getting Started
Finished product
- Create a new Ionic or Angular 2+ Project.
2. Add the @ngrx/store node module to your application.
npm install @ngrx/store --save
For this example, we're using @ngrx/store@5.4.0.
You may also want to add @ngrx/store-devtools for testing.
3. Define the actions for your app in todo/actions.ts.
4. Define the reducer for your app in todo/reducer.ts. (1 or 2)
4. Define the reducer for your app in todo/reducer.ts. (2 of 2)
5. Add the reducer and @ngrx/store module to the app.module.ts file.
6. Test your logic by adding store selectors and dispatched actions to a component . (1 of 2)
6. Test your logic by adding store selectors and dispatched actions to a component . (2 of 2)
7. Define the template for your component.
ngrx - vs - mobx
MobX | NgRx |
---|---|
easier to learn and inject compared to NgRx | has a steeper learning curve than MobX |
the managed state is mutable | the managed state is immutable |
the pattern of implementation is partly up to the developer | the pattern of implementation is more rigid |
not very scalable | more scalable than mobx |
can be harder to test as the app grows | relatively easier to test |
Additional Resources
Next meeting will be held on April 10
;
Ionic @ In3 Session 3
By David Plummer
Ionic @ In3 Session 3
An overview of the state management library NgRx
- 865