Skip to content

Instantly share code, notes, and snippets.

@Conaws
Last active October 19, 2016 09:51
Show Gist options
  • Save Conaws/b06179d73886d22eb07226f1f17c1a21 to your computer and use it in GitHub Desktop.
Save Conaws/b06179d73886d22eb07226f1f17c1a21 to your computer and use it in GitHub Desktop.
Example of how to use re-frame to interact with firebase
(ns re-fire.cljs
(:require [clojure.string :as string]
[cljsjs.firebase]
[re-frame.core :as re-frame :require [dispatch subscribe]]
[reagent.core :as reagent]
[reagent.ratom :as ratom]))
(defn db-ref [path]
(.ref (js/firebase.database) (string/join "/" path)))
(re-frame/reg-sub-raw
:firebase-path
(fn [db [_ path]]
(let [ref (db-ref path)
query-token
(.on ref "value"
(fn [x]
(dispatch [:write-to path (.val x)])))]
(ratom/make-reaction
(fn [] (get-in @db path []))
:on-dispose #(do (.off ref))))))
(re-frame/reg-event-db
:write-to
(fn [db [_ p v]]
(assoc-in db p v)))
(re-frame/reg-event-db
:cleanup
(fn [db [_ p]]
(assoc-in db p {})))
;; this should really go into the appropriate event handler
(defn save [path value]
(.set (db-ref path) value))
(defn test-form [path]
(let [p (r/atom "")
]
(fn []
[:div.flex.flex-v.flex-center
[:input {:value @p
:placeholder "The Test value"
:on-change #(reset! p (-> % .-target .-value))}]
[:button {:on-click #(save path @p)}
"Add to b"]
])))
(defn panel []
(let [demo (subscribe [:firebase-path ["test"]])]
(fn []
[:div "Hey"
[:h1 (pr-str @demo)]
[test-form ["test"]]])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment