1
- import { useState } from 'react' ;
1
+ import { useEffect , useState } from 'react' ;
2
2
import type {
3
3
ToastPropsWithVariant ,
4
4
ToasterProperties ,
@@ -9,6 +9,7 @@ import '../styles/toast-context.css';
9
9
import ToastComponent from './toast' ;
10
10
import { classNames , generateRandomId } from '../utils' ;
11
11
12
+ // Ensure openToastGlobal is initialized correctly
12
13
let openToastGlobal : ( data : ToastPropsWithVariant ) => void ;
13
14
14
15
export const Toaster = ( {
@@ -18,8 +19,13 @@ export const Toaster = ({
18
19
toastFont,
19
20
} : ToasterProperties ) => {
20
21
const [ toasts , setToasts ] = useState < ToastPropsWithVariant [ ] > ( [ ] ) ;
22
+ const [ isMounted , setIsMounted ] = useState < boolean > ( false ) ;
21
23
22
- // Open a new toast:
24
+ useEffect ( ( ) => {
25
+ setIsMounted ( true ) ;
26
+ } , [ ] ) ;
27
+
28
+ // Define the openToast function
23
29
const openToast = ( data : ToastPropsWithVariant ) => {
24
30
const newToast = {
25
31
...data ,
@@ -50,14 +56,17 @@ export const Toaster = ({
50
56
} ) ;
51
57
} ;
52
58
53
- // Close a toast:
59
+ // Define the closeToast function
54
60
const closeToast = ( id : number ) => {
55
61
setToasts ( ( prevToasts ) => prevToasts . filter ( ( toast ) => toast . id !== id ) ) ;
56
62
} ;
57
63
64
+ // Assign openToast to the global variable
58
65
openToastGlobal = openToast ;
59
66
67
+ // Render the component
60
68
return (
69
+ isMounted &&
61
70
toasts . length > 0 && (
62
71
< section
63
72
aria-label = "Toast Notifications"
@@ -86,6 +95,13 @@ export const Toaster = ({
86
95
) ;
87
96
} ;
88
97
98
+ // Export the openToast function:
89
99
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
+ }
91
107
} ;
0 commit comments