Command-Pack for redux
CQS implementation for redux https://martinfowler.com/bliki/CommandQuerySeparation.html
Installation
npm i -S command-pack
Counter Sample
Sample for Counter
First I need to explain what is command
and handler
. Basically a command is just a data dictionary that carries required parameters for the handler
.
To create a command it is needed to make a new brand class that extends command-pack Command
.
Commands:
For our counter sample, we need two commands: First, IncreaseCounter to increase total and DecreaseCounter.
- IncreaseCounter.js
; amount; { super; thisamount = amount; } { return ...state total: statetotal + thisamount ; }
- DecreaseCounter.js
; amount; { super; thisamount = amount; } { return ...state total: statetotal - thisamount ; }
Now we have commands... and they know how to handle this data parameters with handle method by given state
.
Command Registration
; const container = "counterStore" // Store name // Store default state // our commands ;
CommandExecutor
; CommandExecutor;
CommandExecutor.createStore() for Redux-Provider
;;; ; ;;; CommandExecutor; ReactDOM ; ;
Counter React Component
;;;; Component { CommandExecutor; } { CommandExecutor; } { const total = thispropscounterStoretotal; return <div>Counter : total <button onClick=thisdec>decrease</button> <button onClick=thisinc>increase</button> </div> } { return counterStore: xcounterStore}Counter;
ASYNC example
To solve that problem, I tried with middlewares thunk and etc... But it just increases complexity. With command-pack it is really easy to implement an async flow.
Basically you need two commands:
StartDownload
to start flowDownloadCompleted
to get the results
- StartDownload.js
; url; { super; thisurl = url; } { ; return ...state downloading : true ; }
- DownloadCompleted.js
; content; { super; thiscontent = content; } { return ...state downloading : false content : thiscontent ; }