Skip to content

Instantly share code, notes, and snippets.

@Prodge
Last active February 16, 2017 12:41
Show Gist options
  • Save Prodge/914489b49a2470cb3ba545b669c13234 to your computer and use it in GitHub Desktop.
Save Prodge/914489b49a2470cb3ba545b669c13234 to your computer and use it in GitHub Desktop.
re-frame go-swap effect: Push the result pulled from a channel into the db
; Requires this event handler
(reg-event-db :db-swap
(fn [db [_ func value]]
(func db value)))
;The go-swap effect
(reg-fx :go-swap
(fn [[func chan]]
(go (dispatch [:db-swap func (<! chan)]))))
;
; Example Usage:
;
; Mark the start and end of an ajax request in local state.
(reg-event-fx :my-table-refresh
(fn [cofx _]
{:db (assoc-in (:db cofx) [:my-table :refreshing] true)
:go-swap [
(fn [db data]
(-> db
(assoc-in [:my-table :refreshing] false)
(assoc-in [:my-table :rows] data)))
(go (<! (ajax-get! "/my-table/rows")))]}))
; Subscriptions can further be used to drive components to indicate an update is loading.
(reg-sub :is-table-refreshing
(fn [db]
(get-in db [:my-table :refreshing])))
; Example component
(defn refresh-button []
(let [refreshing (subscribe [:is-table-refreshing])]
(fn []
[:div
[:button
(if @refreshing
{:class "disabled"}
{:on-click #(dispatch [:my-table-refresh])})
"Refresh My Table"]])))
(defn matchmaking-table []
(let [rows (subscribe [:my-table-rows])
refreshing (subscribe [:is-table-refreshing])]
(fn []
[:div.matchmaking
[:table
[:tr
[:th "Name"]
[:th "Information"]
(cond
(empty? @rows) [:td {:col-span "99"} "No things found."]
@refreshing [:td {:col-span "99"} [:div.spinner "Loading"]]
:else (for [row @matches]
[build-row row]))]])))
(defn my-table-page []
(fn []
[base
[refresh-button]
[my-table]]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment