diff --git a/web/src/hooks/use-history-back.ts b/web/src/hooks/use-history-back.ts index 764312c7b..d81b037ed 100644 --- a/web/src/hooks/use-history-back.ts +++ b/web/src/hooks/use-history-back.ts @@ -34,7 +34,12 @@ export function useHistoryBack({ // Store the current URL (pathname + search, without hash) before pushing history state urlWhenOpenedRef.current = window.location.pathname + window.location.search; - window.history.pushState({ overlayOpen: true }, ""); + // Preserve existing history state (including React Router state) so that + // navigating back to this entry doesn't lose location.state values + window.history.pushState( + { ...window.history.state, overlayOpen: true }, + "", + ); historyPushedRef.current = true; } @@ -71,4 +76,15 @@ export function useHistoryBack({ urlWhenOpenedRef.current = null; } }, [enabled, open]); + + // Clean up stale history entry if the component unmounts while the overlay + // is still open (e.g. parent component removed from the tree) + React.useEffect(() => { + return () => { + if (historyPushedRef.current) { + historyPushedRef.current = false; + window.history.back(); + } + }; + }, []); }