cassiozen / useStateMachine

The <1 kb state machine hook for React
MIT License
2.38k stars 47 forks source link

Merge send & update in effects #28

Closed cassiozen closed 3 years ago

cassiozen commented 3 years ago

Effects provided two functions as parameters: send & update. In many cases (as illustrated by the async example), send & update will be used together. Maybe instead of two separate functions, we should have an overloaded 'send':

send(event: string)
send(event: string, updater: fn)
send(updater:fn)
dani-mp commented 3 years ago

Could the effect get the current state/context already as a param? Then we wouldn't need an updater function, and the send fn can be just send(event: string, context: any), with the second argument being optional if you want to keep the previous context.

I would go further and create an API that makes it impossible to send more than once within the same effect, to avoid race conditions. Now, you can transition to a different machine state several times within the same effect, and also update the context several times. Both things seem counterintuitive. For instance, what happens if I send and then update?

cassiozen commented 3 years ago

The updater function is useful because you might want to update something based on the current context, like incrementing a counter for example.

RichieAHB commented 3 years ago

If you pass a getContext() thunk as the final parameter for the effect, then this could probably solve your issue with stale context mentioned in this issue https://github.com/cassiozen/useStateMachine/issues/33#issuecomment-850026571 and also remove the need for the updater function (which I assume is also provided to avoid stale access to context)?

dani-mp commented 3 years ago

@cassiozen yeah, that's why I mentioned that the effect function should get the context as a param, or as @RichieAHB mentioned, a function to get the context.

I think if an effect can update the context only once—as suggested in my second paragraph above—, and transition only once, then I don't think how we can end up with a stale context, given that the state machine transitions are synchronous.

cassiozen commented 3 years ago

Please check the proposal in #35 - let's move the discussion over there.