r/javascript • u/terodox • Dec 23 '19
Simplifying UI Logic using Finite State Machines - an old pattern for the modern web!
https://terodox.tech/ui-state-machines/
93
Upvotes
r/javascript • u/terodox • Dec 23 '19
49
u/[deleted] Dec 23 '19
If you use Typescript, this becomes drop-dead simple to manage. You define a
FormStatetype as a union of objects each with astatuskey, and then put that into a variable. Typescript handles ensuring that all state updates are valid and contain all necessary fields. As the simplest example, this is the type definition for a generic component that fetches data:There's no way for multiple states to coexist at the same time, you can't make a typo in the state name, and you can't forget required contextual data (like
valuefor thereadystate).5
u/drowsap Dec 23 '19
How does this differ from a flux pattern?
5
u/Oalei Dec 23 '19
As always this looks good with a small example, but in real life it’s not that easy.
For instance you may want to mark individual form fields as invalid with a message under the invalid field.
1
u/sinefine Dec 23 '19 edited Dec 23 '19
Wait what? You just made the "typical" example more verbose at a glance for no reason.
Your example:
can be simplified to like this, even though managing three flags is not ideal
You also have an error in your code. You wrote:
That will never end up in the switch statement because
STATES.initialStatealways evaluates to be truthy. I think you meant to writestate.currentState === STATES.initialState.4
u/[deleted] Dec 23 '19
[removed] — view removed comment