Skip to content

Commit

Permalink
Fix race condition in backwards compatible way
Browse files Browse the repository at this point in the history
Co-Authored-By: Jared Luxenberg <[email protected]>
  • Loading branch information
timolins and jluxenberg committed Feb 15, 2025
1 parent a9c12f1 commit 1556d28
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 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 { useEffect, useState, useRef } from 'react';
import { DefaultToastOptions, Toast, ToastType } from './types';

const TOAST_LIMIT = 20;
Expand Down Expand Up @@ -143,15 +143,21 @@ export const defaultTimeouts: {

export const useStore = (toastOptions: DefaultToastOptions = {}): State => {
const [state, setState] = useState<State>(memoryState);
const initial = useRef(memoryState);

// TODO: Switch to useSyncExternalStore when targeting React 18+
useEffect(() => {
if (initial.current !== memoryState) {
setState(memoryState);
}
listeners.push(setState);
return () => {
const index = listeners.indexOf(setState);
if (index > -1) {
listeners.splice(index, 1);
}
};
}, [state]);
}, []);

const mergedToasts = state.toasts.map((t) => ({
...toastOptions,
Expand Down

0 comments on commit 1556d28

Please sign in to comment.