Skip to content

Instantly share code, notes, and snippets.

@pesterhazy
Last active August 19, 2016 12:53
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 pesterhazy/07fe0493dd7a2c15bac59464a6e8e853 to your computer and use it in GitHub Desktop.
Save pesterhazy/07fe0493dd7a2c15bac59464a6e8e853 to your computer and use it in GitHub Desktop.
Reagent props, component-did-mount and container components
;; This demonstrates the container component pattern
;; used with reagent (or re-frame)
;;
;; - listen for props changes
;; - inner component (foo-view) gets data passed as prop
;; - outer component (foo) reacts to prop changes by fetching data
;;
;; see https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0
;;
;; For reagent's handling of props, see https://www.martinklepsch.org/posts/props-children-and-component-lifecycle-in-reagent.html
(def state (r/atom {}))
(defn get-data!
"Get data asynchronously. Insert your async request here"
[input]
(make-request input #(swap! state assoc :data %)))
(defn foo-view [data]
[view (pr-str data)])
(defn foo [{:keys [input]}]
(r/create-class
{:component-did-mount #(get-data input)
:component-did-update (fn [this [_ old-p]]
(let [{:keys [input] :as new-p} (r/props this)]
(when (not= new-p old-p)
(get-data! input))))
:reagent-render (fn [] [foo-view (:data @state)])}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment