I got a strange problem. Let's start with my stack, we're using React + NextJS + Tailwind css . I made an toast component using react context, inside my context I have methods which is managing my toasts. Now let's take a look at my code(I cant show all my code , but here is part im getting troubles with) Context file:
export const ToastContextProvider:FC<ToastProps> = ({ children }) => {
const [toasts, setToasts] = useState<ToastComponentProps[]>([]);
const generateId = () => Math.random().toString(36).substring(2, 9);
const removeToast = (_id: string): void => {
setToasts(toasts.filter(({ id }) => id !== _id));
};
const showToast = (toast: ToastComponentProps) => {
const toastWithId = { ...toast, id: generateId() };
setToasts((oldToasts) => [...oldToasts, toastWithId]);
if (toast.timeout !== 0) {
setTimeout(() => removeToast(toastWithId.id), toast.timeout ?? 3000);
}
};
As you can see , every toast object have a proprety name timeout , when timeout = 0 we dont have to remove it automatically by code , and user have to close the toast by himself.
The main problem:
I call a toasts with timeout and without , and they are deleted randomly. I have tried a lot of things but Im still stuck.