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
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@
"goober": "^2.1.16"
},
"peerDependencies": {
"react": ">=16",
"react-dom": ">=16"
"react": ">=18",
"react-dom": ">=18"
}
}
25 changes: 14 additions & 11 deletions src/core/store.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useSyncExternalStore } from 'react';
import { DefaultToastOptions, Toast, ToastType } from './types';

const TOAST_LIMIT = 20;
Expand Down Expand Up @@ -142,16 +142,19 @@ export const defaultTimeouts: {
};

export const useStore = (toastOptions: DefaultToastOptions = {}): State => {
const [state, setState] = useState<State>(memoryState);
useEffect(() => {
listeners.push(setState);
return () => {
const index = listeners.indexOf(setState);
if (index > -1) {
listeners.splice(index, 1);
}
};
}, [state]);
const state = useSyncExternalStore(
(callback) => {
listeners.push(callback);
return () => {
const index = listeners.indexOf(callback);
if (index > -1) {
listeners.splice(index, 1);
}
};
},
() => memoryState,
() => memoryState
);

const mergedToasts = state.toasts.map((t) => ({
...toastOptions,
Expand Down
24 changes: 23 additions & 1 deletion test/toast.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useEffect, useState } from 'react';
import {
render,
screen,
Expand Down Expand Up @@ -319,3 +319,25 @@ test('pause toast', async () => {

expect(toastElement).not.toBeInTheDocument();
});

test('"toast" can be called from useEffect hook', async () => {
const MyComponent = () => {
const [success, setSuccess] = useState(false);
useEffect(() => {
toast.success('Success toast');
setSuccess(true);
}, []);

return success ? <div>MyComponent finished</div> : null;
};

render(
<>
<MyComponent />
<Toaster />
</>
);

await screen.findByText(/MyComponent finished/i);
expect(screen.queryByText(/Success toast/i)).toBeInTheDocument();
});