Skip to content

Instantly share code, notes, and snippets.

@g-todorov
Created December 16, 2022 08:28
Show Gist options
  • Save g-todorov/f435c4db79842593d032e03026a71e9d to your computer and use it in GitHub Desktop.
Save g-todorov/f435c4db79842593d032e03026a71e9d to your computer and use it in GitHub Desktop.
xstate-typed-children-machines
import React from "react";
import { Text } from "react-native";
import { useActor } from "@xstate/react";
import { ChildMachineActor } from "../machines/childMachine";
interface Props {
actor: ChildMachineActor;
}
export function ChildComponent({ actor }: Props) {
const [state, send] = useActor(actor);
return <Text>{`${state.value}`}</Text>;
}
import { ActorRefFrom, createMachine } from "xstate";
export const childMachine = createMachine(
{
context: {},
schema: {},
tsTypes: {} as import("./childMachine.typegen").Typegen0,
id: "child",
initial: "idle",
states: {
idle: {},
},
},
{
actions: {},
services: {},
}
);
export type ChildMachineActor = ActorRefFrom<typeof childMachine>;
import React from "react";
import { ChildComponent } from "./childComponent";
import { useMachine } from "@xstate/react";
import { parentMachine } from "../machines/parentMachine";
export function ParentComponent() {
const [state, send] = useMachine(parentMachine);
return state.context.childRef ? (
<ChildComponent actor={state.context.childRef}></ChildComponent>
) : null;
}
import { ActorRefFrom, createMachine, spawn, assign } from "xstate";
import { childMachine, ChildMachineActor } from "./childMachine";
export const parentMachine = createMachine(
{
context: {
childRef: null,
},
schema: { context: {} as { childRef: null | ChildMachineActor } },
tsTypes: {} as import("./parentMachine.typegen").Typegen0,
id: "parent",
initial: "idle",
states: {
idle: { entry: "assignChildRef" },
},
},
{
actions: {
assignChildRef: assign({
childRef: (context, event) => {
return spawn(childMachine, { name: "childMachine" });
},
}),
},
services: {},
}
);
export type parentMachineActor = ActorRefFrom<typeof parentMachine>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment