statelyai / xstate

Actor-based state management & orchestration for complex app logic.
https://stately.ai/docs
MIT License
26.98k stars 1.24k forks source link

Bug: The type signature of spawn method is wrong if used with setup().createMachine() #4811

Closed loicdesirest closed 6 months ago

loicdesirest commented 6 months ago

XState version

XState version 5

Description

In the "friends-list-react" example you can find the following action spawning a friendMachine

createMachine({
  // other props skipped...
  on: {
    'FRIENDS.ADD': {
          guard: ({ event }) => event.name.trim().length > 0,
          actions: assign({
            friends: ({ context, spawn }) =>
              context.friends.concat(
                spawn(friendMachine, {
                  id: `friend-${makeId()}`,
                  input: {
                    name: context.newFriendName
                  }
                })
              ),
            newFriendName: ''
          })
      }
  }
});

The code use the createMachine function exported by xState and this works just fine. But if you switch to the syntaxe using the TS infered type for spawn will be bad

setup({/* Your setup code */}).createMachine({
  // other props skipped...
  on: {
    'FRIENDS.ADD': {
      // actual spawn code
    }
  }
})

Expected result

Capture d’écran du 2024-03-21 13-41-16

Actual result

Capture d’écran du 2024-03-21 13-42-06

Reproduction

https://stackblitz.com/edit/github-qtmqpx?file=src%2FfriendsMachine.ts

Additional context

I'm using Xstate 5.9.1 and I provided a stackblitz link so you can easily see the issue (inside friendsMachine.ts)

loicdesirest commented 6 months ago

So it's not a bug but documentation is lacking (or at least not clear) You need to declare your actors in the setup() method and then use a string to refer to them. Capture d’écran du 2024-03-21 13-56-25