Description
When sending event during entry of an initial state it seems the xstate.init event gets fired twice. This ends up causing the entrys to get fired twice for the app I'm working on. I've provided a simplified example.
The main thing we're trying to accomplish is having a state that mainly drives our UI states and transitions and a parallel one that handles background tasks, especially the initial fetching of data. I'm noticing in our we're double fetching the initial data because of this. We have a workaround, but curious if a) this is intended behavior and if so b) just curious what's a suggested approach.
Expected Result
xstate.init should only be sent once to services for an identical machine.
Actual Result
xstate.init sent twice.
Reproduction
https://codesandbox.io/s/withered-brook-5e1u9?file=/src/index.tsx
Additional context
This happens because "initial actions" are scheduled for executions both here:
https://github.com/davidkpiano/xstate/blob/02ef7a0b22e7ede5a49999b783b6573b54b65c7c/packages/xstate-react/src/useMachine.ts#L91
and here:
https://github.com/davidkpiano/xstate/blob/02ef7a0b22e7ede5a49999b783b6573b54b65c7c/packages/xstate-react/src/useMachine.ts#L107
because onTransition fires its callback synchronously with whatever "latest" transition.
A good thing though is that this no longer happens with our latest @xstate/react developments on https://github.com/davidkpiano/xstate/pull/1202
The xstate.init event no longer fires twice in the latest @xstate/react RC.
Most helpful comment
This happens because "initial actions" are scheduled for executions both here:
https://github.com/davidkpiano/xstate/blob/02ef7a0b22e7ede5a49999b783b6573b54b65c7c/packages/xstate-react/src/useMachine.ts#L91
and here:
https://github.com/davidkpiano/xstate/blob/02ef7a0b22e7ede5a49999b783b6573b54b65c7c/packages/xstate-react/src/useMachine.ts#L107
because
onTransitionfires its callback synchronously with whatever "latest" transition.A good thing though is that this no longer happens with our latest
@xstate/reactdevelopments on https://github.com/davidkpiano/xstate/pull/1202