reading the channel makes me question about how I use reagent and re-frame.. this is a typical view function from my app
(defn main-panel []
(let [fund-filters-loaded? @(rf/subscribe [:fund.filters.subs/loaded])
logged-profile @(rf/subscribe [:logged-profile])]
[:<>
[chart]
(if fund-filters-loaded?
[:<>
[filters {:suspended-enabled? false
:custom-filter #(custom-filter logged-profile)}]
[fund-list callback]]
[:div "loading..."])]))
this is a form-1 component according to reagent documentation
my question is, should it be form-2 and return a function instead?
@wvelezva what you wrote works. re-frame caches subscriptions, so when your component re-renders it will get the same subscription value every time
the reason you'd use a form-2 is it if you wanted something to only run on component mount (first render)
e.g.:
(defn my-component []
(let [count (r/atom 0)]
[:button {:on-click #(swap! count inc)} @count]))
☝️ that would re-create the count
atom every render, so it would always say "0"
(defn my-component []
(let [count (r/atom 0)]
(fn []
[:button {:on-click #(swap! count inc)} @count])))
☝️ that will create the count
atom on first render, and then only run the inner function each subsequent oneI understand, and that is not desirable so in my case with the subscriptions?
and only make the dereference in the inner fn?
(defn main-panel []
(let [fund-filters-loaded? (rf/subscribe [:fund.filters.subs/loaded])
logged-profile (rf/subscribe [:logged-profile])]
(fn []
[:<>
[chart]
(if @fund-filters-loaded?
[:<>
[filters {:suspended-enabled? false
:custom-filter #(custom-filter @logged-profile)}]
[fund-list callback]]
[:div "loading..."])])))
like I said above, you can use either a form-1 or form-2 because re-frame caches subscriptions
(rf/subscribe [:fund.filters.subs/loaded])
will return the same thing every time
it will only create the subscription once
so you may use it in a form-1
so is a matter of taste?
use form-2 if and only if, you are dealing with local states i.e using reagent to manage form state
yes it's a matter of taste
other than that its preferred to use form 1
form 1 makes component simpler
since it only does one thing, renders component
😌
thanks a lot!
how ever, if you still want to use form 1 component while managing local state
you can do that
there is a trick
I’m all ears….
(defn simple-form [args]
(reagent/with-let
[state (reagent/atom {:username ""})]
[:form
[:input {:type :text
:placeholder :username
:on-change #(swap! state assoc :username (-> % .-target .-value))
:value (:username @state)}]]))
the trick is to wrap the component with with-let
function
and voila, no more form-2
the code I inherited had those with-let
plus the subscriptions, when I started learning I didn’t see any difference between with-let
and the “simple” let
so I adopted that style
thanks @lilactown and @vishal.gautam
Anyone know if it is possible to configure the React Dev Tools to highlight updates to Reagent components? 🤞