Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Atoms can't be initiated in a function or a let? #24

Closed
Frozenlock opened this issue Mar 5, 2014 · 2 comments
Closed

Atoms can't be initiated in a function or a let? #24

Frozenlock opened this issue Mar 5, 2014 · 2 comments

Comments

@Frozenlock
Copy link

(def at (atom "hello"))

[my-awesome-widget at]

Works as expected.
However, if I try to create the atom in a function, or in a let, it doesn't work.

[my-awesome-widget 
  (let [aa (atom "hello")]
    aa)]

In the latter case, it seems that any attempt to change the atom (from within my-awesome-widget) will fail.

@holmsand
Copy link
Contributor

holmsand commented Mar 6, 2014

That's because you create a new atom every time my-awesome-widget runs in the second example, which means that it will always have the value "hello".

To make it convenient to use local atoms like that, Reagent allows you to return a new function from the component, that will be called in the future when the component has changed. Like this:

(defn timer-component []
  (let [seconds-elapsed (atom 0)]
    (fn []
      (js/setTimeout #(swap! seconds-elapsed inc) 1000)
      [:div
       "Seconds Elapsed: " @seconds-elapsed])))

The returned function will be called with exactly the same arguments as the top-level function.

You can see that in action here: http://holmsand.github.io/reagent/index.html

@holmsand holmsand closed this as completed Mar 6, 2014
@Frozenlock
Copy link
Author

Ah! Of course!
And I already read this tutorial. Shame that I forgot about this after only a few hours.

My apologies, seems like some of my Clojure reflexes are hard to shed. ;-)

Thanks for Reagent by the way, it's amazing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants