Skip to content

Instantly share code, notes, and snippets.

@hosmelq
Created March 31, 2021 20:21
Show Gist options
  • Save hosmelq/95e64da9a0a10d1f18fd05cc8c4dabec to your computer and use it in GitHub Desktop.
Save hosmelq/95e64da9a0a10d1f18fd05cc8c4dabec to your computer and use it in GitHub Desktop.

Revisions

  1. hosmelq created this gist Mar 31, 2021.
    51 changes: 51 additions & 0 deletions machine.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    import {createMachine, createSchema} from 'xstate'

    import {assign} from '@xstate/immer'

    import {ToastProps} from 'components/Toast'

    type AddToastEvent = {
    type: 'ADD_TOAST'
    toast: ToastProps
    }

    type RemoveToastEvent = {
    index: number
    type: 'REMOVE_TOAST'
    }

    export const toastMachine = createMachine(
    {
    schema: {
    context: createSchema<{toasts: ToastProps[]}>(),
    events: createSchema<AddToastEvent | RemoveToastEvent>(),
    },
    context: {
    toasts: [],
    },
    id: 'toast-manager',
    initial: `idle`,
    states: {
    idle: {
    on: {
    ADD_TOAST: {
    actions: 'addToast',
    },
    REMOVE_TOAST: {
    actions: 'removeToast',
    },
    },
    },
    },
    },
    {
    actions: {
    addToast: assign((ctx, e) => {
    ctx.toasts.push(e.toast)
    }),
    removeToast: assign((ctx, e) => {
    ctx.toasts.splice(e.index, 1)
    }),
    },
    }
    )