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.
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)
}),
},
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment