Skip to content
Source
Sign inSign up
samwillis/one-million-boxes
Open History to see the last commit

ErrorToast.tsx

53 lines1.3 KB

1import { useEffect, useState } from "react"
2import { useGameStateContext } from "../../contexts/game-state-context"
3import "./ErrorToast.css"
4​
5const TOAST_DURATION_MS = 4000
6​
7/**
8 * Shows error messages from game state.
9 * Positioned at the bottom above the footer.
10 */
11export function ErrorToast() {
12 const { error } = useGameStateContext()
13 const [visible, setVisible] = useState(false)
14 const [displayedError, setDisplayedError] = useState<string | null>(null)
15​
16 useEffect(() => {
17 if (error) {
18 setDisplayedError(error)
19 setVisible(true)
20​
21 const timer = setTimeout(() => {
22 setVisible(false)
23 }, TOAST_DURATION_MS)
24​
25 return () => clearTimeout(timer)
26 } else {
27 // Immediately hide when error is cleared
28 setVisible(false)
29 }
30 }, [error])
31​
32 // Handle animation end to clear displayed error
33 const handleAnimationEnd = () => {
34 if (!visible) {
35 setDisplayedError(null)
36 }
37 }
38​
39 if (!displayedError) {
40 return null
41 }
42​
43 return (
44 <div
45 className={`error-toast ${visible ? `error-toast--visible` : `error-toast--hidden`}`}
46 onAnimationEnd={handleAnimationEnd}
47 data-testid="error-toast"
48 >
49 <span className="error-toast__icon">!</span>
50 <span className="error-toast__message">{displayedError}</span>
51 </div>
52 )