Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | 10x 10x 10x 10x 5x 5x 5x 5x 3x 3x 3x 5x 1x 5x 1x 5x 1x 5x 1x 10x | import { ReactNode, createContext, useContext, useState } from 'react'
import { Toast, ToastParams } from './Toast'
export type ToastContextProps = {
toast: (message: string) => void
toastSuccess: (message: string) => void
toastError: (message: string) => void
}
const ToastContext = createContext<ToastContextProps>({} as ToastContextProps)
/**
* Hook to access toast context
*/
const useToastContext = () => useContext(ToastContext)
/**
* Provider element to wrap other elements to access toast context
* @see {@link useToastContext}
*/
function ToastProvider({ children }: { children: ReactNode }) {
const [showToast, setShowToast] = useState(false)
const [type, setType] = useState<ToastParams['type']>('default')
const [text, setText] = useState('')
const _toast = (toastType: typeof type, message: string) => {
setType(toastType)
setText(message)
setShowToast(true)
}
const toast = (message: string) => {
_toast('default', message)
}
const toastSuccess = (message: string) => {
_toast('success', message)
}
const toastError = (message: string) => {
_toast('error', message)
}
return (
<ToastContext.Provider
value={{
toast,
toastSuccess,
toastError,
}}
>
{children}
{showToast && <Toast type={type} text={text} onClose={() => setShowToast(false)} />}
</ToastContext.Provider>
)
}
export { useToastContext, ToastProvider }
|