An opinionated toast component for React.
Add hooks to show active toasts (#347)
Muhammad Rizqi Tsani42400e9d36c0
diff --git a/src/index.tsx b/src/index.tsxindex c197836..7dad581 100644--- a/src/index.tsx+++ b/src/index.tsx@@ -437,6 +437,33 @@ function getDocumentDirection(): ToasterProps['dir'] {return dirAttribute as ToasterProps['dir'];}+function useSonner() {+ const [activeToasts, setActiveToasts] = React.useState<ToastT[]>([]);++ React.useEffect(() => {+ return ToastState.subscribe((toast) => {+ setActiveToasts((currentToasts) => {+ if ('dismiss' in toast && toast.dismiss) {+ return currentToasts.filter((t) => t.id !== toast.id);+ }++ const existingToastIndex = currentToasts.findIndex((t) => t.id === toast.id);+ if (existingToastIndex !== -1) {+ const updatedToasts = [...currentToasts];+ updatedToasts[existingToastIndex] = { ...updatedToasts[existingToastIndex], ...toast };+ return updatedToasts;+ } else {+ return [toast, ...currentToasts];+ }+ });+ });+ }, []);++ return {+ toasts: activeToasts,+ };+}+const Toaster = (props: ToasterProps) => {const {invert,@@ -485,8 +512,12 @@ const Toaster = (props: ToasterProps) => {const isFocusWithinRef = React.useRef(false);const removeToast = React.useCallback(- (toast: ToastT) => setToasts((toasts) => toasts.filter(({ id }) => id !== toast.id)),- [],+ (toastToRemove: ToastT) => {+ if (!toasts.find((toast) => toast.id === toastToRemove.id)?.delete) {+ ToastState.dismiss(toastToRemove.id);+ }+ },+ [toasts],);React.useEffect(() => {@@ -690,4 +721,4 @@ const Toaster = (props: ToasterProps) => {</section>);};-export { toast, Toaster, type ToastT, type ExternalToast };+export { toast, Toaster, type ToastT, type ExternalToast, useSonner };