|
| 1 | +import { useEffect, useRef } from 'react'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Hook to handle automatic toast dismissal based on duration |
| 5 | + * |
| 6 | + * @param duration - Duration in milliseconds before the toast automatically disappears |
| 7 | + * @param id - The unique ID of the toast |
| 8 | + * @param hide - Function to hide the toast |
| 9 | + * |
| 10 | + * @example |
| 11 | + * ```tsx |
| 12 | + * useToastDuration(4000, toastId, hide); |
| 13 | + * ``` |
| 14 | + */ |
| 15 | +export function useToastDuration( |
| 16 | + duration: number | null | undefined, |
| 17 | + id: string | undefined, |
| 18 | + hide: ((ids?: string | string[]) => void) | undefined |
| 19 | +): void { |
| 20 | + const timeoutRef = useRef<NodeJS.Timeout | null>(null); |
| 21 | + |
| 22 | + useEffect(() => { |
| 23 | + // Clear any existing timeout |
| 24 | + if (timeoutRef.current) { |
| 25 | + clearTimeout(timeoutRef.current); |
| 26 | + timeoutRef.current = null; |
| 27 | + } |
| 28 | + |
| 29 | + // Only set timeout if duration is valid and id/hide are available |
| 30 | + if ( |
| 31 | + duration !== null && |
| 32 | + duration !== undefined && |
| 33 | + !isNaN(duration) && |
| 34 | + duration > 0 && |
| 35 | + duration !== Infinity && |
| 36 | + id && |
| 37 | + hide |
| 38 | + ) { |
| 39 | + timeoutRef.current = setTimeout(() => { |
| 40 | + hide(id); |
| 41 | + }, duration); |
| 42 | + } |
| 43 | + |
| 44 | + // Cleanup timeout on unmount or when duration/id/hide changes |
| 45 | + return () => { |
| 46 | + if (timeoutRef.current) { |
| 47 | + clearTimeout(timeoutRef.current); |
| 48 | + timeoutRef.current = null; |
| 49 | + } |
| 50 | + }; |
| 51 | + }, [duration, id, hide]); |
| 52 | +} |
0 commit comments