Set up re-frame and take a pass at the sketch index

This commit is contained in:
Jeremy Dormitzer 2018-04-01 10:09:01 -04:00
parent 6627dd2adb
commit 862851bdfd
No known key found for this signature in database
GPG Key ID: 04F17C0F5A32C320
4 changed files with 70 additions and 10 deletions

View File

@ -1,19 +1,35 @@
(ns sketchbook.core
(:require [reagent.core :as r]))
(:require [reagent.core :as r]
[re-frame.core :refer [dispatch subscribe]]
[sketchbook.events]
[sketchbook.subs]))
(defonce state (r/atom {:thing "world"}))
(defn sketch [sketch-item width height]
[:div {:key (:path sketch-item)}
[:h1 (:title sketch-item)]
[:img {:src (str "/api/sketches/"
(:path sketch-item)
"?width=" width
"&height=" height)
:width width
:height height}]])
(defn hello []
[:div
[:h1 (str "Hello " (:thing @state)"!")]
[:button {:onClick (fn [] (swap! state #(assoc % :thing "universe")))}
"Universe"]
[:button {:onClick (fn [] (swap! state #(assoc % :thing "world")))}
"World"]])
(defn sketches []
(let [sketch-list @(subscribe [:sketches])
loading @(subscribe [:loading-sketches])]
(if loading
[:div "Loading..."]
(if (> (count sketch-list) 0)
[:div
(map #(sketch % 300 300) sketch-list)]
[:div "No sketches found"]))))
(defn app []
[:div
[hello]])
[sketches]])
(dispatch [:initialize])
(dispatch [:fetch-sketches])
(r/render [app]
(.getElementById js/document "app"))

View File

@ -0,0 +1,5 @@
(ns sketchbook.db)
(def initial-db
{:sketches []
:loading-sketches false})

View File

@ -0,0 +1,27 @@
(ns sketchbook.events
(:require [re-frame.core :refer [reg-event-db reg-event-fx]]
[ajax.core :as ajax]
[day8.re-frame.http-fx]
[sketchbook.db :as db]))
(reg-event-db
:initialize
(fn [_ _]
db/initial-db))
(reg-event-fx
:fetch-sketches
(fn [{db :db} _]
{:http-xhrio {:method :get
:uri "/api/sketches"
:format (ajax/json-request-format)
:response-format (ajax/json-response-format {:keywords? true})
:on-success [:sketches-fetched]}
:db (assoc db :loading-sketches true)}))
(reg-event-db
:sketches-fetched
(fn [db [_ response]]
(-> db
(assoc :loading-sketches false)
(assoc :sketches (js->clj response)))))

View File

@ -0,0 +1,12 @@
(ns sketchbook.subs
(:require [re-frame.core :refer [reg-sub]]))
(reg-sub
:sketches
(fn [db _]
(:sketches db)))
(reg-sub
:loading-sketches
(fn [db _]
(:loading-sketches db)))