Skip to content

Instantly share code, notes, and snippets.

@mainej
Created October 25, 2021 05:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mainej/c9621864d3cb7423a1efc8942d65a606 to your computer and use it in GitHub Desktop.
Save mainej/c9621864d3cb7423a1efc8942d65a606 to your computer and use it in GitHub Desktop.
Example of `glimt.multi-state`
(ns test-glimt.views
(:require
[reagent.core :as r]
[re-frame.core :as re-frame]
[glimt.multi-state :as http]
[ajax.json :as ajax]
[day8.re-frame.http-fx]
))
;; once, at app load
(re-frame/dispatch [::http/register {:id :one-retry
:max-retries 1}])
(defn request [org]
{:fsm/id :one-retry
:request/id [:repos org]
:http-xhrio {:uri (str "https://api.github.com/orgs/" org "/repos")
:method :get
:response-format (ajax/json-response-format {:keywords? true})}
#_#_:on-loading [::prn :org/loading org]
#_#_:on-error [::prn :org/error org]
#_#_:on-failure [::prn :org/failure org]
:on-success [::loaded org]
#_#_:path [:repos org]
})
(re-frame/reg-fx ::prn prn)
(re-frame/reg-event-fx
::prn
(fn [_ args]
{::prn args}))
(re-frame/reg-event-fx
::loaded
(fn [{:keys [db]} [_ org result :as args]]
{;; ::prn (concat [:org/loaded] args)
:db (assoc-in db [:repos org] result)
:fx [[:dispatch-later {:ms 1000, :dispatch [::http/discard [:repos org]]}]]}))
(re-frame/reg-sub ::repos #(get % :repos))
(re-frame/reg-sub
::repo :<- [::repos]
(fn [repos [_ org]]
(get repos org)))
(defn org-details [org]
(r/with-let [request (request org)
state (re-frame/subscribe [::http/state (:request/id request)])
repos (re-frame/subscribe [::repo org])]
(let [[primary-state secondary-state] @state
repos @repos
loaded? (seq repos)]
[:div
[:h1 org]
[:div "Repo count: " (if loaded? (count repos) "Unknown")]
(case primary-state
nil
[:button {:on-click #(re-frame/dispatch [::http/start request])}
(if loaded? "Refresh" "Load")]
::http/loading
[:div "Loading..."]
::http/error
[:div "An error occurred"
(case secondary-state
::http/retrying
[:div "Please wait, trying again"]
::http/halted
[:div
"Could not load data"
[:div
[:button {:on-click #(re-frame/dispatch [::http/restart (select-keys request
[:fsm/id
:request/id])])}
"Try again"]]])]
::http/loaded
[:div "Loaded!"])])))
(defn main-panel []
[:div
[org-details "cognitect"]
[org-details "jmaine"]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment