Skip to content

Instantly share code, notes, and snippets.

@magick93
Created April 15, 2024 22:15
Show Gist options
  • Save magick93/f3f343fdca82b3983ea5f41e7f74d5c7 to your computer and use it in GitHub Desktop.
Save magick93/f3f343fdca82b3983ea5f41e7f74d5c7 to your computer and use it in GitHub Desktop.
Confirm delete FSM
import { assign, createMachine, fromPromise } from 'xstate';
import { setup } from 'xstate';
function executeAction() {
console.log('FSM: Executing action...');
};
export interface ConfirmationDialogMachineContext {
action?: Promise<void>;
errorMessage?: string;
}
type ConfirmationDialogMachineEvent =
| {
type: 'OPEN_DIALOG';
action: void;
}
| {
type: 'CONFIRM';
}
| {
type: 'CANCEL';
};
const confirmationDialogMachine = setup<ConfirmationDialogMachineContext, ConfirmationDialogMachineEvent>(
{
id: 'confirmationDialog',
initial: 'closed',
context: {} as { row: any },
events: {} as ConfirmationDialogMachineEvent,
actors: {
executeAction:executeAction
},
states: {
closed: {
id: 'closed',
on: {
OPEN_DIALOG: {
target: 'open',
actions: 'assignActionToContext',
},
},
},
open: {
exit: ['clearErrorMessage'],
initial: 'idle',
states: {
idle: {
on: {
CANCEL: '#closed',
CONFIRM: {
target: 'executingAction'
},
},
},
executingAction: {
invoke: {
src: 'executeAction',
id: 'executeAction',
src: 'executeAction',
onError: {
target: 'idle',
actions: 'assignErrorMessageToContext',
},
onDone: {
target: '#closed',
actions: ['clearActionFromContext', 'onSuccess'],
},
},
},
},
},
},
},
{
// services: {
// executeAction: (context) => () => {
// console.log('Executing action...');
// // For demonstration purposes, I've commented this out.
// // await context.action()
// },
// },
// actions: {
// assignActionToContext: assign((context, event) => {
// console.log('Assigning action to context...');
// console.log('context', context);
// console.log('event', event);
// if (context.event.type !== 'OPEN_DIALOG') return {};
// return {
// action: context.event.action,
// };
// }),
// assignErrorMessageToContext: assign((context, event: any) => {
// return {
// errorMessage: event.data?.message || 'An unknown error occurred',
// };
// }),
// clearErrorMessage: assign({
// errorMessage: undefined,
// }),
// clearActionFromContext: assign({
// action: undefined,
// }),
// onSuccess: () => {
// alert('onSuccess fired!');
// },
// },
},
);
// .createMachine({ initial: "idle" });
export default confirmationDialogMachine;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment