Last active
August 19, 2016 12:53
-
-
Save pesterhazy/07fe0493dd7a2c15bac59464a6e8e853 to your computer and use it in GitHub Desktop.
Reagent props, component-did-mount and container components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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