Giter VIP home page Giter VIP logo

Comments (11)

orestis avatar orestis commented on July 25, 2024

I'm hijacking this issue to discuss about something that caught me a little bit unawares with Atomified.

I had this code:

(let [foo (<-state #{})]
 [:button {:on-click (fn [e] (swap! foo conj 1)
                                            (js/console.log @foo))}])

I would expect based on my Clojure experience that #{1} should be printed, but because react hasn't re-rendered anything yet, the value of the deref-ed state is still the original empty set.

I tried to work around this by relying on the return value of swap! which should be the new value, but the implementation of Atomified doesn't return anything.

I now wonder if the semantics of a Clojure atom make sense for this rendering lifecycle that React uses, where the new state is only available after a re-render.

from hx.

orestis avatar orestis commented on July 25, 2024

A workaround for this is to manually update the deref-ed value, and then reset! it into the new state to trigger the rendering. So something like this:

(fn [e]
  (let [new-foo (conj foo 1)]
      (reset! foo new-foo)
      (js/console.log new-foo)))

from hx.

lilactown avatar lilactown commented on July 25, 2024

Hm. Yeah, useState is more like an agent than an atom, since updates are scheduled by React asynchronously.

And it schedules the update itself, not the value, so it's impossible to return the correct value from swap! without bugs.

from hx.

lilactown avatar lilactown commented on July 25, 2024

I think that we want to maintain the semantics of useState because it is the most correct when used in Concurrent React.

The question then is: do we drop the atom interface?

from hx.

orestis avatar orestis commented on July 25, 2024

Good point. I like the ergonomics of seeing a deref in the code, and the usual atom stuff do look convenient. But, it does seem like a leaky abstraction. Using the plain useState isn’t that painful, and the semantics are actually less surprising. So perhaps dropping the atom interface is best at this point. Or at least documenting this with great big letters.

from hx.

orestis avatar orestis commented on July 25, 2024

Re-reading this, I think @Lokeh you are up to something by saying "useState is more like an agent". I've never used Agents before, but reading the documentation I think it's definitely possible to expose this kind of semantics (or the subset that makes sense).

So for example instead of using the swap! and reset! which point to atoms and synchronous updates, we'd use send (or perhaps send->) that would just call setFoo behind the scenes.

Deref is still a thing with agents, but you get whatever the current value is, because the update happens on a different thread outside of your control.

from hx.

mhuebert avatar mhuebert commented on July 25, 2024

I find myself wondering exactly what sort of bugs one might find when using ordinary atom semantics.

Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase). Doing so will lead to confusing bugs and inconsistencies in the UI. [link]

It looks to me like one could adopt plain atom semantics, with the caveat that it is unsafe to reset/swap the atom during the render phase? This would be similar to allowed behaviour in class components:

 Warning: setState(...): Cannot update during an existing state transition 
(such as within `render` or another component's constructor). Render methods 
 should be a pure function of props and state; constructor side-effects are an anti-pattern, 
 but can be moved to `componentWillMount`.

One could have something like deferred-swap! or send for the exceptional case of wanting to trigger a state update from within the render. I'm not sure what the uses for that are, or if there are other reasons/places where synchronous mutations would be unsafe.

from hx.

orestis avatar orestis commented on July 25, 2024

The issue I had was that I was assuming that inside the click handler I could access the new atom state:

(let [foo (<-state #{})]
  [:button {:on-click (fn [e] (swap! foo conj 1)
                        (js/console.log @foo))}])

Had foo been an actual Clojure/Script atom, then swap! would be a blocking call and @foo would get the new value.

What I am proposing is something like:

(let [foo (<-state #{})]
  [:button {:on-click (fn [e] (send-> foo conj 1)
                        (js/console.log @foo))}])

The result would be exactly the same -- @foo will still give me the pre-render value (an empty set), but now as a consumer of the API I find it less confusing, because it's not an atom -- it's just something that I can deref.

Ideally one could also attach a validator to catch invalid states but that's a second step.

from hx.

mhuebert avatar mhuebert commented on July 25, 2024

yes - I understand the use-case; my question is, why not provide a state API such that swap! and reset! are synchronous operations, since it would appear to be a safe API to implement, with the caveat that the atom shouldn't be mutated during render.

from hx.

orestis avatar orestis commented on July 25, 2024

There are subtle interplays with useEffect that Lokeh has found out. We should collect all this discussions into a single page because it’s spread out over many issues and PRs etc.

from hx.

lilactown avatar lilactown commented on July 25, 2024

Closing this for now.

What I've done is kept <-ref as an atom, and changed <-state to return [value set-value] tuple.

The set-value function can be used like swap! e.g. (set-value assoc :key new-value)

from hx.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.