ChrisShank / xstate-vue2

Vue 2 composables for XState.
MIT License
19 stars 5 forks source link

Update useMachine.ts #3

Closed liutao closed 2 years ago

liutao commented 3 years ago

We attempt to use useMachine with Actor model in vue, but I noticed the entry with print two times. After debug, useInterpret will print one time, and service.machine. initialState will print another time. In the source code spawn depend on a service, but execute service.machine. initialState directly, service will be undefined now. service.machine will provide this first, this.machine.initialState will get the correct service.

const { Machine, interpret, assign, createMachine, sendParent, send, spawn } = require('xstate');
const remoteMachine = createMachine({
  id: 'remote',
  initial: 'offline',
  states: {
    offline: {
      on: {
        WAKE: 'online'
      }
    },
    online: {
      after: {
        1000: {
          actions: sendParent('REMOTE.ONLINE')
        }
      }
    }
  }
});

const parentMachine = createMachine({
  id: 'parent',
  initial: 'waiting',
  context: {
    localOne: null
  },
  states: {
    waiting: {
      entry: assign({
        localOne: () => {
          console.log('entry');
          return spawn(remoteMachine);
        }
      }),
      on: {
        'LOCAL.WAKE': {
          actions: send({ type: 'WAKE' }, { to: (context) => context.localOne })
        },
        'REMOTE.ONLINE': { target: 'connected' }
      }
    },
    connected: {}
  }
});
const parentService = interpret(parentMachine)
  .onTransition((state) => console.log(state.value))
  .start();

console.log(parentService.initialState.context);  // print entry once, context.localOne is Interpreter(Actor)
console.log(parentService.machine.initialState.context); // print entry twice, context.localOne  will be nullActor(https://github.com/statelyai/xstate/blob/68692c1d11df7a513e68d4ce888603c1ffe41552/packages/core/src/Actor.ts#L29) 
ChrisShank commented 3 years ago

Thanks for debugging this, ill try to take a look later today!

ChrisShank commented 3 years ago

@liutao I am able to reproduce this, quite an interesting bug! (FYI here is a reproduder https://codesandbox.io/s/focused-voice-hnuni?file=/src/main.ts). I have raised this issue with https://github.com/statelyai/xstate since this might affect multiple packages like @xstate/react and @xstate/vue. I just want to confirm with @davidkpiano that this is not a problem with xstate core. Otherwise I will merge and release a patch as soon as possible!

ChrisShank commented 2 years ago

Just waiting for a response on whether this is a bug that should be fixed with core before merging. https://github.com/statelyai/xstate/issues/2457

ChrisShank commented 2 years ago

Released 0.2.1 to patch this. Thanks for contributing again! let me know if you need anything else