Created
March 2, 2023 21:33
-
-
Save cambiata/fde337965d14532d10b919ee0155ce81 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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