better error handling

This commit is contained in:
thesn10
2026-06-26 19:13:17 +02:00
parent 94d2d67e83
commit 12f1344138
3 changed files with 40 additions and 16 deletions

View File

@@ -2,24 +2,26 @@
import { createContext, useCallback, useContext, useState, type ReactNode } from 'react'
const ToastCtx = createContext<(msg: string) => void>(() => {})
type ToastFn = (msg: string, type?: 'success' | 'error') => void
const ToastCtx = createContext<ToastFn>(() => {})
export function useToast() {
return useContext(ToastCtx)
}
export function ToastProvider({ children }: { children: ReactNode }) {
const [msg, setMsg] = useState('')
const [state, setState] = useState<{ msg: string; type: 'success' | 'error' } | null>(null)
const show = useCallback((m: string) => {
setMsg(m)
setTimeout(() => setMsg(''), 2800)
const show = useCallback<ToastFn>((m, type = 'success') => {
setState({ msg: m, type })
setTimeout(() => setState(null), type === 'error' ? 4500 : 2800)
}, [])
return (
<ToastCtx.Provider value={show}>
{children}
{msg && (
{state && (
<div
style={{
position: 'fixed',
@@ -32,7 +34,7 @@ export function ToastProvider({ children }: { children: ReactNode }) {
gap: 10,
padding: '12px 18px',
background: 'var(--bg2)',
border: '1px solid var(--accBd)',
border: `1px solid ${state.type === 'error' ? 'var(--errBd, #f87171)' : 'var(--accBd)'}`,
borderRadius: 12,
boxShadow: '0 16px 40px rgba(0,0,0,.55)',
fontSize: 13,
@@ -46,12 +48,12 @@ export function ToastProvider({ children }: { children: ReactNode }) {
width: 8,
height: 8,
borderRadius: '50%',
background: 'var(--acc2)',
boxShadow: '0 0 8px var(--acc2)',
background: state.type === 'error' ? '#f87171' : 'var(--acc2)',
boxShadow: state.type === 'error' ? '0 0 8px #f87171' : '0 0 8px var(--acc2)',
flexShrink: 0,
}}
/>
{msg}
{state.msg}
</div>
)}
</ToastCtx.Provider>