From 8d1d575215d118987db1b42c24a9f20d85079366 Mon Sep 17 00:00:00 2001 From: Paul Bienkowski Date: Mon, 12 Sep 2022 17:42:22 +0200 Subject: [PATCH] Debounce map moves before writing browser history (fixes #276) --- frontend/src/components/Map/index.tsx | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/frontend/src/components/Map/index.tsx b/frontend/src/components/Map/index.tsx index 0ce11a1..3c0b35d 100644 --- a/frontend/src/components/Map/index.tsx +++ b/frontend/src/components/Map/index.tsx @@ -44,19 +44,32 @@ function buildHash(v: Viewport): string { return `${v.zoom.toFixed(2)}/${v.latitude}/${v.longitude}`; } +const setViewportToHash = _.debounce((history, viewport) => { + history.replace({ + hash: buildHash(viewport), + }); +}, 200); + function useViewportFromUrl(): [Viewport | null, (v: Viewport) => void] { const history = useHistory(); const location = useLocation(); - const value = useMemo(() => parseHash(location.hash), [location.hash]); + + const [cachedValue, setCachedValue] = useState(parseHash(location.hash)); + + // when the location hash changes, set the new value to the cache + useEffect(() => { + setCachedValue(parseHash(location.hash)); + }, [location.hash]); + const setter = useCallback( (v) => { - history.replace({ - hash: buildHash(v), - }); + setCachedValue(v); + setViewportToHash(history, v); }, [history] ); - return [value || EMPTY_VIEWPORT, setter]; + + return [cachedValue || EMPTY_VIEWPORT, setter]; } function Map({