Skip to content

Instantly share code, notes, and snippets.

@magick93
Last active April 16, 2024 01:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magick93/1e2bdaa54cfbd24ed08d9c8e9b39b47b to your computer and use it in GitHub Desktop.
Save magick93/1e2bdaa54cfbd24ed08d9c8e9b39b47b to your computer and use it in GitHub Desktop.
xstate invoke
import { assign, setup } from 'xstate';
function executeAction() {
console.log('executing action');
}
export type ConfirmationDialogMachineEvent =
| { type: 'OPEN_DIALOG'; action: void }
| { type: 'CONFIRM' }
| { type: 'CANCEL' };
const confirmDialogueMachine = setup({
types: {
events: {} as ConfirmationDialogMachineEvent,
context: {} as {
isOpen: boolean;
action: void | (() => void);
},
},
actors: {
executeAction: executeAction,
},
}).createMachine({
id: 'confirmDialogue',
initial: 'closed',
context: {
isOpen: false,
action: undefined,
},
states: {
idle: {},
closed: {
on: {
OPEN_DIALOG: {
target: 'open',
actions: assign({
isOpen: true,
// action: (_, event) => event.action,
}),
},
},
},
executingAction: {
invoke: {
src: 'executeAction',
id: 'executeAction',
onDone: {
target: 'idle',
actions: assign({
isOpen: false,
}),
},
onError: {
target: 'idle',
actions: assign({
isOpen: false,
}),
},
},
},
open: {
initial: "idle" ,
on: {
CONFIRM: 'executingAction',
// target: 'executingAction',
// actions: [
// assign({
// isOpen: false,
// }),
// (context) => {
// if (context.action) {
// context.action();
// }
// },
// ],
// },
CANCEL: {
target: 'closed',
actions: assign({
isOpen: false,
}),
},
},
states: {
idle: {},
executingAction: {
invoke: {
src: 'executeAction',
id: 'executeAction',
onDone: {
target: 'idle',
actions: assign({
isOpen: false,
}),
},
onError: {
target: 'idle',
actions: assign({
isOpen: false,
}),
},
},
},
},
},
},
});
export { confirmDialogueMachine };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment