From f35eb42d7b7ea2ade7573146dcf1f443ab890d7a Mon Sep 17 00:00:00 2001 From: James Grugett Date: Wed, 5 Oct 2022 13:27:46 -0500 Subject: [PATCH] Make search query params work on page load --- web/hooks/use-persistent-state.ts | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/web/hooks/use-persistent-state.ts b/web/hooks/use-persistent-state.ts index 090aa264..4448bb77 100644 --- a/web/hooks/use-persistent-state.ts +++ b/web/hooks/use-persistent-state.ts @@ -1,12 +1,13 @@ import { useEffect } from 'react' import { useStateCheckEquality } from './use-state-check-equality' -import { NextRouter } from 'next/router' +import { NextRouter, useRouter } from 'next/router' export type PersistenceOptions = { key: string; store: PersistentStore } export interface PersistentStore { get: (k: string) => T | undefined set: (k: string, v: T | undefined) => void + readsUrl?: boolean } const withURLParam = (location: Location, k: string, v?: string) => { @@ -61,6 +62,7 @@ export const urlParamStore = (router: NextRouter): PersistentStore => ({ window.history.replaceState(updatedState, '', url) } }, + readsUrl: true, }) export const historyStore = (prefix = '__manifold'): PersistentStore => ({ @@ -102,5 +104,20 @@ export const usePersistentState = ( store.set(key, state) } }, [key, state]) + + if (store?.readsUrl) { + // On page load, router isn't ready immediately, so set state once it is. + + // eslint-disable-next-line react-hooks/rules-of-hooks + const router = useRouter() + // eslint-disable-next-line react-hooks/rules-of-hooks + useEffect(() => { + if (router.isReady) { + const savedValue = key != null ? store.get(key) : undefined + setState(savedValue ?? initial) + } + }, [router.isReady]) + } + return [state, setState] as const }