timolins / react-hot-toast

Smoking Hot React Notifications 🔥
https://react-hot-toast.com
MIT License
9.55k stars 313 forks source link

fix: toast not appearing when toast.* called from useEffect hook #251

Open jluxenberg opened 1 year ago

jluxenberg commented 1 year ago

Issues

Cause

The useStore hook (used by Toaster) calls "useState" to get the current state of the global memoryState, and then calls "useEffect" to set up a subscription to the global memoryState.

The bug is caused when a change to the global memoryState happens after "useState" is called, but before the "useEffect" callback is run. This can happen e.g. if we call a toast.* function from within another component's useEffect hook.

Solution

Use the useSyncExternalStore hook instead of useState and useEffect; it handles these cases correctly.

I've added a dependency on the use-sync-external-store shim so that React version below 18 are still supported.

Related Github issues

https://github.com/timolins/react-hot-toast/issues/101 https://github.com/timolins/react-hot-toast/issues/57 https://github.com/timolins/react-hot-toast/issues/142 https://github.com/timolins/react-hot-toast/issues/253

vercel[bot] commented 1 year ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
react-hot-toast ❌ Failed (Inspect) May 4, 2023 4:48pm
cmmartin commented 1 year ago

I am also experiencing this bug. toast called inside useEffect do not show. or show sometime later which is not desired

jluxenberg commented 1 year ago

@timolins Any chance of getting this merged? I just merged main into it so should be good to go. Let me know if there's anything I can do to help!

brandanking-decently commented 8 months ago

Hey, has anything changed with getting this fixed or merged into main. This problem still seems to be hanging around. Thanks