Created
March 31, 2021 20:21
-
-
Save hosmelq/95e64da9a0a10d1f18fd05cc8c4dabec to your computer and use it in GitHub Desktop.
This file contains 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, 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