I'm trying to make toast notifications in my project by myself and I'm almost there but I have a little problem now. I set up my notifications and made it disappear on click. But then I added setTimeout to remove toast from my state after 5 seconds and it doesn't work as I expected. When there is one notification it works as it should, but when there is more that one notifications it removes all the toasts, and then brings back all except the last one. I think there is a problem with my setState action in removeToast function.
Deleting one by one works properly.
Code:
const useToastsContainer = createContainer(() => {
const [toasts, setToasts] = useState<ToastItem[]>([]);
useEffect(() => {
console.log(toasts);
}, [toasts]);
const removeToast = (id: string) => {
setToasts(toasts.filter((item) => item.id !== id));
};
const createToast = (type: ToastType, content: string) => {
const id = v4();
const toast = {
id,
type,
content,
};
setToasts([...toasts, toast]);
setTimeout(() => {
removeToast(id);
}, 5000);
};
return {
toasts,
removeToast,
createToast,
};
});