Forget about react/angular/flux/redux, design your app first — part 2/3
Part 2: design the redux-like store component
In part 1 of this article, we designed the overall architecture and create the interface of view component. We also provided two abstract view classes in order to help us build our view.
In the second part, we will focus on the store component, which manages the application state and handles the business logic with reducers. (a redux-like pattern)
We create a class to represent the store interface:
The constructor takes an object as the second argument for the initial state.
It has 4 methods:
- dispatch(action): usually this will be called when a view sent an action. It dispatches the action to reducers/action handlers registered in this store
- handleAction(actionType, handler): add an action handler to handle an action
- reduce(actionType, reducer): use a reducer to handle action, redux style. This is just a different way to call handleAction
- registerView(name, view): register a view to this store, so that the store can notify state changes
A basic implementation
Now we have the interface, it is time to implement it. Here is the basic version:
With this store component, you can change your previous counter application’s business logic with this store component.
If you run this app, you will see two counters, and they share the same state (change one counter will make another one change too).
Visualise the store component data flow
As what we did for the view component, you can implement a different store component with collar.js and visualise the data flow and action flow with collar dev server.
If you use the collar.js based view implementation (introduced at the end of the part 1) with this collar.js based store component implementation, you can visualise the data flow in collar dev server on http://localhost:7500:
In this part 2, We designed a redux-like store component interface, and implemented two version of it: one basic version and another one with collar.js to visualise the data flow.
Both of these two versions take about 50 lines of code. You get a centralised state management store and a redux-like reducer to handle the action.