Skip to content

Commit 069d485

Browse files
committed
fix: update Toaster component, ensure rendering of toasts
1 parent 71872ef commit 069d485

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

library/src/components/toaster.tsx

+20-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useState } from 'react';
1+
import { useEffect, useState } from 'react';
22
import type {
33
ToastPropsWithVariant,
44
ToasterProperties,
@@ -9,6 +9,7 @@ import '../styles/toast-context.css';
99
import ToastComponent from './toast';
1010
import { classNames, generateRandomId } from '../utils';
1111

12+
// Ensure openToastGlobal is initialized correctly
1213
let openToastGlobal: (data: ToastPropsWithVariant) => void;
1314

1415
export const Toaster = ({
@@ -18,8 +19,13 @@ export const Toaster = ({
1819
toastFont,
1920
}: ToasterProperties) => {
2021
const [toasts, setToasts] = useState<ToastPropsWithVariant[]>([]);
22+
const [isMounted, setIsMounted] = useState<boolean>(false);
2123

22-
// Open a new toast:
24+
useEffect(() => {
25+
setIsMounted(true);
26+
}, []);
27+
28+
// Define the openToast function
2329
const openToast = (data: ToastPropsWithVariant) => {
2430
const newToast = {
2531
...data,
@@ -50,14 +56,17 @@ export const Toaster = ({
5056
});
5157
};
5258

53-
// Close a toast:
59+
// Define the closeToast function
5460
const closeToast = (id: number) => {
5561
setToasts((prevToasts) => prevToasts.filter((toast) => toast.id !== id));
5662
};
5763

64+
// Assign openToast to the global variable
5865
openToastGlobal = openToast;
5966

67+
// Render the component
6068
return (
69+
isMounted &&
6170
toasts.length > 0 && (
6271
<section
6372
aria-label="Toast Notifications"
@@ -86,6 +95,13 @@ export const Toaster = ({
8695
);
8796
};
8897

98+
// Export the openToast function:
8999
export const openToast = (data: ToastPropsWithVariant): void => {
90-
openToastGlobal(data);
100+
if (openToastGlobal) {
101+
openToastGlobal(data);
102+
} else {
103+
console.error(
104+
'🔔 <Toaster /> component is not mounted. Check toast.pheralb.dev/toaster for more information.',
105+
);
106+
}
91107
};

0 commit comments

Comments
 (0)