Skip to content

Instantly share code, notes, and snippets.

@roman01la
Last active April 28, 2017 16:17
Show Gist options
  • Save roman01la/d4e5acc08fb5b455438fe84255933ab0 to your computer and use it in GitHub Desktop.
Save roman01la/d4e5acc08fb5b455438fe84255933ab0 to your computer and use it in GitHub Desktop.
(defmulti control (fn [action] action))
(defmethod control :init [_ _ _]
{:state {:count 0}}) ;; <= initial state effect
(defmethod control :inc [_ _ state]
{:state (update state :count inc)}) ;; <= increment state effect
(defmethod control :load [_ [id] _]
{:http {:uri (str "/api/count/" id)
:on-success :load-ready
:on-fail :load-fail}}) ;; <= HTTP effect
(defmethod control :load-fail [_ [error] state]
{:state (assoc state :error error)}) ;; <= load error state effect
(defmethod control :load-ready [_ [response] state]
{:state (assoc state :count response)}) ;; <= load success state effect
(defmethod control :persist [_ _ state]
{:local-storage {:method :set
:key :my-app/counter
:data (-> state clj->js js/JSON.stringify)}}) ;; <= persist localStorage effect
(defmethod control :read-persist [_ _ _]
{:local-storage {:method :get
:key :my-app/counter
:on-read :read-persist-ready}}) ;; <= read persist localStorage effect
(defmethod control :read-persist-ready [_ [data] state]
{:state (->> data js/JSON.parse js->clj)}) ;; <= read persist localStorage success effect
;; ===========================
(def r
(scrum/reconciler
{:state (atom {})
:controllers {:counter counter/control}}
:effects {:http effects/http
:local-storage effects/local-storage}))
(scrum/broadcast-sync! :init)
(scrum/dispatch! :counter :load 5)
;; ===========================
(defn http [reconciler controller {:keys [uri on-success on-fail]}]
(-> (httpurr/get uri)
(p/then #(scrum/dispatch! reconciler controller on-success %))
(p/catch #(scrum/dispatch! reconciler controller on-fail %))))
(defn local-storage [reconciler controller {:keys [method key data on-read]}]
(case method
:set (js/localStorage.setItem (str key) data)
:get (->> (js/localStorage.getItem (str key)) (scrum/dispatch! reconciler controller on-read))
nil))
@DjebbZ
Copy link

DjebbZ commented Apr 28, 2017

Line 18 why not simply return response ? In this proposal, the control controller isn't responsible directly for the state at the key :counter ? What is the value of the state parameter in the controller methods ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment