DEV Community

Discussion on: No, disabling a button is not app logic.

Collapse
 
uriklar profile image
Uri Klar

Hi David, Thanks a lot for this write up.
One thing that wasn't very clear to me is the cancelling logic in the reducer example.

  • The cleanup function is inside the

    if (state.status === "loading")

    block. So how is it still being invoked when status changes to "idle"? (due to a cancel event)

  • How does the cleanup variable persist across renders?

In general i'd love a few words on cancelation logic since it doesn't look very trivial.
Thanks again!

Collapse
 
uriklar profile image
Uri Klar

Same question, but regarding the XState example.
What makes the cancelation logic work? Does the onDone function not get invoked if the src promise has resolved but we have since transitioned to a different state?

Collapse
 
gmaclennan profile image
Gregor MacLennan

I had this question too, and eventually found the answer in the docs

If the state where the invoked promise is active is exited before the promise settles, the result of the promise is discarded.

The invoke property seems like a little bit of "magic" in XState and it took me a while to understand what is actually happening there.

David, thanks for writing this, having a concrete example really helped understand XState and I look forward to seeing more.

Collapse
 
uriklar profile image
Uri Klar

Ok, so after debugging the sandbox a bit I think I get it...
The cleanup function (that turns canceled into true) only runs when state changes from loading to something else (because it is only returned in the loading state).
So... if we've changed from loading to idle before the promise has returned, when it returns the canceled flag will be true and it will return without doing anything.

I do however feel that this logic kind of goes against what this entire post is trying to advocate: declarative, easy to understand logic.

I'm wondering if maybe there's a more "state machiney" way to implement this functionality (without going full on state machine like in the last example)

Collapse
 
davidkpiano profile image
David K. 🎹

Yes there is, and Reason has done it - reasonml.github.io/reason-react/do...

Collapse
 
sapegin profile image
Artem Sapegin

I also stumbled over this example and agree that explicit cancelation would make the app logic easier to understand. Implicit cancelation feels too close to the isLoadingΒ from the very first example.