timolins / react-hot-toast

Smoking Hot React Notifications 🔥
https://react-hot-toast.com
MIT License
9.47k stars 310 forks source link

How to avoid having multiple toasts on screen? #289

Open siyao-polarr opened 1 year ago

siyao-polarr commented 1 year ago

Is there an option to have a new toast replace the current toast instead of adding on?

pandeymangg commented 1 year ago

https://react-hot-toast.com/docs/toast

See the "prevent duplicate toasts" section

camkon commented 1 year ago

to limit the number of toasts shown on screen, customize the toaster component like

import { useEffect } from "react";
import toast, { Toaster, useToasterStore } from "react-hot-toast";

const ToasterComponent = () => {
    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]);

    return (<Toaster maxCount={1} />)
};

export default ToasterComponent

Hope this helps