Skip to content

Instantly share code, notes, and snippets.

@benzen
Last active September 6, 2015 11:22
Show Gist options
  • Save benzen/dac5018371fd124fa3c7 to your computer and use it in GitHub Desktop.
Save benzen/dac5018371fd124fa3c7 to your computer and use it in GitHub Desktop.
Rookie mistake with local state

Theses are two implmentation of the same components. The component is a label, with two button, one to increase the counter, and one to decrease.

The counter's value can't go bellow zero.

In the first implmentation, there is a tiny bit of logic that is miss placed. This logic is executed when the component is rendered. This is bad because the effect of this logic will never appear.

On the second implementaition the "previous-value" is computed with a corrected value (min 0). So everything is in place when the dec button is pressed. And we don't need to render cycle to get the correct result.

(defn counter []
(let [value (r/atom 0)]
(fn []
(let [current-value @value
inc-value #(swap! value inc)
dec-value #(reset! value dec)
reset-value #(reset! value 0)]
(if (< current-value 0) (reset-value))
[:div
[:p (str "Counter is" current-value)]
[:button {:on-click inc-value} "Increment"]
[:button {:on-click dec-value} "Decrement"]]))))
(defn counter []
(let [value (r/atom 0)]
(fn []
(let [inc-value #(swap! value inc )
dec-value #(swap! value #(if (< % 1 ) 0 (dec %))]
[:div
[:p (str "Counter is" @value)]
[:button {:on-click inc-value} "Increment"]
[:button {:on-click dec-value} "Decrement"]]))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment