Xstate: Xstate.init sent multiple times to services

Created on 29 May 2020  路  2Comments  路  Source: davidkpiano/xstate

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

bug 鈿涳笌 @xstatreact

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 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

All 2 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jfun picture jfun  路  3Comments

drmikecrowe picture drmikecrowe  路  3Comments

3plusalpha picture 3plusalpha  路  3Comments

bradwoods picture bradwoods  路  3Comments

carlbarrdahl picture carlbarrdahl  路  3Comments