Skip to content

Commit

Permalink
Add hooks to show active toasts (#347)
Browse files Browse the repository at this point in the history
  • Loading branch information
rizqitsani authored Feb 23, 2024
1 parent 85486f0 commit 42400e9
Showing 1 changed file with 34 additions and 3 deletions.
37 changes: 34 additions & 3 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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(() => {
Expand Down Expand Up @@ -690,4 +721,4 @@ const Toaster = (props: ToasterProps) => {
</section>
);
};
export { toast, Toaster, type ToastT, type ExternalToast };
export { toast, Toaster, type ToastT, type ExternalToast, useSonner };

0 comments on commit 42400e9

Please sign in to comment.