Typescript, Actor and useActor problem #1534
-
Hi, I'm trying to upgrade to I have no idea how to type spawned actor in main machine to pass it to child component and use this actor in Thanks 🙏 |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 3 replies
-
Have exactly the same issue. I can of course just set the prop I am passing in to I have tried:
Our usecase is the same as @RafalFilipek 's. We are spawning a machine in a parent machine and pass the reference down to a child component so that it can be used in there. Previously our typing for that reference was
Any help would be much appreciated, otherwise we would probably have to downgrade again :-) |
Beta Was this translation helpful? Give feedback.
-
Have you tried this locally? There are tests that show that typings work with spawned machines: https://github.com/davidkpiano/xstate/blob/master/packages/core/test/actor.test.ts#L79-L140 So I'm wondering if this is a CodeSandbox + TypeScript issue. |
Beta Was this translation helpful? Give feedback.
-
The section you have highlighted uses E.g. in my specific case it was saying:
But digging in error messages can sometimes help, so I think the solution for typing the actor correctly is:
Or. more generically:
Doing it that way I get everthing nicely typed 👍 |
Beta Was this translation helpful? Give feedback.
-
Updated example with |
Beta Was this translation helpful? Give feedback.
-
This PR would address/fix this issue: #1622 Notably, it:
const childMachine = createMachine(...);
interface SomeContext {
machineRef?: ActorRefFrom<typeof childMachine>
}
const parentMachine = createMachine<SomeContext>({
// ...
entry: assign({
machineRef: (ctx, e) => spawn(childMachine)
})
});
// ... in a component
const ChildComponent: React.FC<{ child: ActorRefFrom<typeof childMachine> }> = ({ child }) => {
const [state, send] = useActor(child);
// ...
} |
Beta Was this translation helpful? Give feedback.
This PR would address/fix this issue: #1622
Notably, it:
ActorRef<TEvent, TEmitted>
type to be compatible with the v4Actor<...>
types thatspawn(...)
returnsActorRefFrom<SomeMachine>
to make it easier to type spawned machines: