Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Add useUrlState hook

Joshen Lim371e3c575156
diff --git a/studio/hooks/ui/index.ts b/studio/hooks/ui/index.ts
index 257a28147d7..a62409a29de 100644
--- a/studio/hooks/ui/index.ts
+++ b/studio/hooks/ui/index.ts
@@ -1,2 +1,3 @@
export * from './useFlag'
export * from './useIsActive'
+export * from './useUrlState'
diff --git a/studio/hooks/ui/useUrlState.ts b/studio/hooks/ui/useUrlState.ts
new file mode 100644
index 00000000000..3d22de107e2
--- /dev/null
+++ b/studio/hooks/ui/useUrlState.ts
@@ -0,0 +1,54 @@
+import { useCallback } from 'react'
+import { useRouter } from 'next/router'
+
+type UrlStateParams = {
+ [k: string]: string | string[] | undefined
+}
+
+export function useUrlState({
+ replace = true,
+ arrayKeys = [],
+}: {
+ /** Whether to use push state routing (working back button), or just replace the current URL
+ * @default true
+ */
+ replace?: boolean
+ arrayKeys?: string[]
+} = {}) {
+ const arrayKeysSet = new Set(arrayKeys)
+ const router = useRouter()
+
+ const params: UrlStateParams = Object.fromEntries(
+ Object.entries(router.query).map(([key, value]) => {
+ if (arrayKeysSet.has(key)) {
+ console.log(value)
+ return Array.isArray(value) ? [key, value] : [key, [value]]
+ }
+
+ return [key, value]
+ })
+ )
+
+ const setParams = useCallback(
+ (newParams: UrlStateParams | ((previousParams: UrlStateParams) => UrlStateParams)) => {
+ const nextParams = typeof newParams === 'function' ? newParams(params) : newParams
+ let newQuery = Object.fromEntries(
+ Object.entries({ ...params, ...nextParams }).filter(([, value]) => Boolean(value))
+ )
+
+ const replaceOrPush = replace ? router.replace : router.push
+
+ replaceOrPush(
+ {
+ pathname: router.pathname,
+ query: newQuery,
+ },
+ undefined,
+ { shallow: true, scroll: false }
+ )
+ },
+ [router, params, replace]
+ )
+
+ return [params, setParams]
+}