7
votes

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:

  1. Store
  2. Reducer and
  3. Action

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.

2
When an action is dispatched, it is passed to every reducer. So, no, you cannot have multiple actions with the same name.cartant
@cartant - How ngrx then force users to not have actions with same name? In a big app there can be hundreds of action and there is a possibility of action name clash.Ritesh Waghela
It's up to you to make sure your actions have distinct types. If you want, scope them as is done in the the example app.cartant
A pretty clean explanation by the devs behid ngrx/store during ng-conf: youtube.com/watch?v=cyaAhXHhxgkJota.Toledo

2 Answers

3
votes

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'.