Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -683,7 +683,7 @@ const Toaster = React.forwardRef<HTMLElement, ToasterProps>(function Toaster(pro
});
});
});
}, [toasts]);
}, []);

React.useEffect(() => {
if (theme !== 'system') {
Expand Down
11 changes: 10 additions & 1 deletion src/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,18 @@ class Observer {
subscribe = (subscriber: (toast: ToastT | ToastToDismiss) => void) => {
this.subscribers.push(subscriber);

// Replay toasts queued before this subscriber attached (issue #723).
for (const toast of this.toasts) {
if ('dismiss' in toast && (toast as ToastToDismiss).dismiss) continue;
if (this.dismissedToasts.has(toast.id)) continue;
subscriber(toast);
}

return () => {
const index = this.subscribers.indexOf(subscriber);
this.subscribers.splice(index, 1);
if (index !== -1) {
this.subscribers.splice(index, 1);
}
};
};

Expand Down
25 changes: 25 additions & 0 deletions test/src/app/issue-723/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
'use client';

import React from 'react';
import { Toaster, toast } from 'sonner';

// Sibling rendered ABOVE <Toaster /> — its useEffect runs before the Toaster's,
// so toast() fires before ToastState has a subscriber. See issue #723.
function ToastOnMount() {
const fired = React.useRef(false);
React.useEffect(() => {
if (fired.current) return;
fired.current = true;
toast('Toast fired before Toaster subscribed');
}, []);
return null;
}

export default function Issue723Page() {
return (
<>
<ToastOnMount />
<Toaster />
</>
);
}
6 changes: 6 additions & 0 deletions test/tests/basic.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -337,4 +337,10 @@ test.describe('Basic functionality', () => {
await expect(page.getByTestId('promise-test-toast')).toHaveText('Loading...');
await expect(page.getByTestId('promise-test-toast')).toHaveText('Loaded');
});

// Regression for https://github.com/emilkowalski/sonner/issues/723
test('toast fired before Toaster subscribes is still displayed', async ({ page }) => {
await page.goto('/issue-723');
await expect(page.getByText('Toast fired before Toaster subscribed')).toHaveCount(1);
});
});