DEV Community

San
San

Posted on

How to prevent multiple times react-hot-toast easily

How to prevent multiple times react-hot-toast easily
You can achieve by using useToasterStore() & useEffect().

Restrict the maximum number of Toasts to show in React Toast component. You can restrict the maximum toast count by event callback function.

  1. You need to import useToasterStore hook from react-hot-toast

Copy/paste the given snippet into your code.

const { toasts } = useToasterStore();

const TOAST_LIMIT = 1

useEffect(() => {
  toasts
    .filter((t) => t.visible) // Only consider visible toasts
    .filter((_, i) => i >= TOAST_LIMIT) // Is toast index over limit?
    .forEach((t) => toast.dismiss(t.id)); // Dismiss – Use toast.remove(t.id) for no exit animation
}, [toasts]);

Enter fullscreen mode Exit fullscreen mode

Output

It will show only one times. If you want to show multiple time you can put the number in that variable: const TOAST_LIMIT = 1

Top comments (0)