I am trying my hands on ngrx library for managing the state of my application. I have gone through many ngrx documents and git pages. I understand that there are three important concept:
Store is the single source of data for our application. So any modification or retrieval of data is done through Actions. My question here is what exactly happens when an action is dispatched to the store? How does it know which reducers is to be invoked? Does it parses all the reducers registered to the store? There can be multiple actions with the same name in that case what happens?
Thanks in advance.
Yes - all the reducers will get called when you dispatch the action.
Reducers in NgRx are responsible for handling transitions from one state to the next state in your application. Reducer functions handle these transitions by determining which actions to handle based on the type.
store. dispatch(action) : Sends an action through all the reducers. store.
Most effects are straightforward: they receive a triggering action, perform a side effect, and return an Observable stream of another action which indicates the result is ready. NgRx effects will then automatically dispatch that action to trigger the reducers and perform a state change.
A picture is worth a thousand words...
Source: Building a Redux Application with Angular2
Example Code: ngrx-todo-app
Demo: Todo App using @ngrx/store and @ngrx/effects
My question here is what exactly happens when an action is dispatched to the store? All of the registered reducers get a chance to handle the action
How does it know which reducers is to be invoked? All of the registered reducers get invoked. Try putting console.logs into all the reducers and you can see for yourself.
Does it parses all the reducers registered to the store? Yes
There can be multiple actions with the same name in that case what happens? If you have multiple actions with the same name they would be treated the same. For example if I dispatched type "ADD" with payload 3 and then dispatched a different action called type "ADD" with payload 3 it would be the same thing.
Ngrx isn't that smart. Let's say we have the following reducers:
const reducers = { blog: BlogReducer, post: PostReducer, comment: CommentReducer }
Say I dispatch 'ADD_COMMENT'. Basically BlogReducer will first try to handle it, followed by PostReducer, and finally by CommentReducer. The ordering is determined by how you specified the reducers object above. So if I did this:
const reducers = { comment: CommentReducer, blog: BlogReducer, post: PostReducer }
CommentReducer would be the first one to try and handle the 'ADD_COMMENT'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With