Created
August 17, 2020 15:07
-
-
Save smnplk/2eb6f5bcdd855c7fcef9744e4c59a0d9 to your computer and use it in GitHub Desktop.
Example of re-frame effect handlers and event handlers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defonce interval-handler | |
(let [live-intervals (atom {})] | |
(fn handler [{:keys [action id frequency event]}] | |
(condp = action | |
:clean (doall | |
(map #(handler {:action :end :id %}) (keys @live-intervals))) | |
:start (swap! live-intervals assoc id (js/setInterval #(rf/dispatch event) frequency)) | |
:end (do | |
(js/clearInterval (get @live-intervals id)) | |
(swap! live-intervals dissoc id)))))) | |
(rf/reg-fx | |
:interval | |
interval-handler) | |
(rf/reg-cofx | |
:local-store | |
(fn [coeffects local-store-key] | |
(assoc coeffects | |
:local-store | |
(util/read-transit (.getItem js/localStorage local-store-key))))) | |
(rf/reg-fx | |
:local-store-add | |
(fn [data] | |
(doseq [[key val] data] | |
(.setItem js/localStorage key (util/write-transit val))))) | |
(rf/reg-event-fx | |
:login | |
(fn [{db :db} [_ {:keys [values path]}]] | |
{:db (fork/set-submitting db path true) | |
:http-xhrio {:method :post | |
:uri "/login" | |
:timeout 8000 | |
:format (ajax/transit-request-format) | |
:params values | |
:response-format (ajax/transit-response-format) | |
:on-success [:login-success path] | |
:on-failure [:login-failure path]}})) | |
(rf/reg-event-fx | |
:login-success | |
(fn [{:keys [db] :as cfx} [_ path result]] | |
(let [auth-token (:auth-token result) | |
refresh-token (:refresh-token result) | |
{:keys [user-data exp]} (util/decode-auth-token auth-token) | |
new-db (-> (assoc db :user user-data | |
:active-page :home-page) | |
(fork/set-submitting path false))] | |
{:db new-db | |
:local-store-add {"auth-token" auth-token | |
"refresh-token" refresh-token ;; todo, do not store refresh token in ls, store it in httpOnly cookie | |
"exp" exp | |
"db" new-db} | |
:interval {:action :start | |
:id :refresh-auth-token | |
:frequency 400000 | |
:event [:refresh-auth-token]}}))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment