Files
supabase/apps/studio/hooks/misc/useSchemaQueryState.ts
T
Ivan Vasilov 8c6d0f1890 feat: Save the selected schema in the URL and local storage (#28662)
* Add nuqs package.

* Add useSchemaQueryState hook.

* Use the new hook in all places where there's is a schema selector.

* Make the useQueryState work with SSR in playwright.

* Fix the saving to local storage to happen as a side effect without any additional rerenders.
2024-08-19 13:28:25 +02:00

37 lines
1.3 KiB
TypeScript

import { parseAsString, useQueryState } from 'nuqs'
import { useParams } from 'common'
import { LOCAL_STORAGE_KEYS } from 'lib/constants'
/**
* This hook wraps useQueryState because useQueryState imports app router for some reason which breaks the SSR in
* the playwright tests. I've localized the issue to "NODE_ENV='test'" in the playwright tests.
*/
const useIsomorphicUseQueryState = (defaultSchema: string) => {
if (typeof window === 'undefined') {
return [defaultSchema, () => {}] as const
} else {
// eslint-disable-next-line react-hooks/rules-of-hooks
return useQueryState('schema', parseAsString.withDefault(defaultSchema))
}
}
export const useQuerySchemaState = () => {
const { ref } = useParams()
let defaultSchema = 'public'
if (typeof window !== 'undefined') {
defaultSchema =
window.localStorage.getItem(LOCAL_STORAGE_KEYS.LAST_SELECTED_SCHEMA(ref ?? '')) || 'public'
}
const [schema, setSelectedSchema] = useIsomorphicUseQueryState(defaultSchema)
// Update the schema to local storage on every change
if (defaultSchema !== schema && typeof window !== 'undefined') {
window.localStorage.setItem(LOCAL_STORAGE_KEYS.LAST_SELECTED_SCHEMA(ref ?? ''), schema)
}
return { selectedSchema: schema, setSelectedSchema }
}