Skip to content

Instantly share code, notes, and snippets.

@cambiata
Created March 2, 2023 21:33
Show Gist options
  • Save cambiata/fde337965d14532d10b919ee0155ce81 to your computer and use it in GitHub Desktop.
Save cambiata/fde337965d14532d10b919ee0155ce81 to your computer and use it in GitHub Desktop.
import { createMachine, interpret, send, sendParent, assign } from 'xstate';
type Child1Context =
| { type: 'empty' }
| { type: 'data', value: number }
| { type: 'error', msg: string }
const child1Machine = createMachine<Child1Context>({
id: 'timer',
initial: 'active',
context: { type: 'empty' },
states: {
active: {
invoke: {
src: (context, event) => new Promise((res, rej) => {
setTimeout(() => {
res(12345)
// rej('This is an error');
}, 1000)
}),
onDone: {
target: 'finished',
actions: assign((context, event): Child1Context => { return { type: 'data', value: event.data } })
},
onError: {
target: 'finished',
actions: assign((context, event): Child1Context => { return { type: 'error', msg: event.data } })
}
}
},
finished: {
type: 'final',
data: (context, event): Child1Context => context,
}
}
});
type ParentContext = {
child1: Child1Context,
}
const parentMachine = createMachine<ParentContext>({
id: 'parent',
initial: 'pending',
context: {
child1: { type: 'empty' },
},
states: {
pending: {
invoke: {
src: child1Machine,
onDone: 'timesUp',
}
},
timesUp: {
entry: assign((context, event) => { return { ...context, child1: event.data } }),
type: 'final',
}
}
});
const service = interpret(parentMachine)
.onTransition((state) => console.log(state.value, JSON.stringify(state.context)))
.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment