Skip to content

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

fix: Fix the caching of the selected schema (#28999)

Ivan Vasilov24f590e893f3
diff --git a/apps/studio/hooks/misc/useSchemaQueryState.ts b/apps/studio/hooks/misc/useSchemaQueryState.ts
index 22313eedf31..b0e183c6bd2 100644
--- a/apps/studio/hooks/misc/useSchemaQueryState.ts
+++ b/apps/studio/hooks/misc/useSchemaQueryState.ts
@@ -1,4 +1,5 @@
import { parseAsString, useQueryState } from 'nuqs'
+import { useEffect, useMemo } from 'react'
import { useParams } from 'common'
import { LOCAL_STORAGE_KEYS } from 'lib/constants'
@@ -19,18 +20,22 @@ const useIsomorphicUseQueryState = (defaultSchema: string) => {
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 defaultSchema =
+ typeof window !== 'undefined' && ref && ref.length > 0
+ ? window.localStorage.getItem(LOCAL_STORAGE_KEYS.LAST_SELECTED_SCHEMA(ref)) || 'public'
+ : 'public'
- const [schema, setSelectedSchema] = useIsomorphicUseQueryState(defaultSchema)
+ // cache the original default schema so that it's not changed by another tab and cause issues in the app (saving a
+ // table on the wrong schema)
+ const originalDefaultSchema = useMemo(() => defaultSchema, [ref])
+ const [schema, setSelectedSchema] = useIsomorphicUseQueryState(originalDefaultSchema)
- // 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)
- }
+ useEffect(() => {
+ // Update the schema in local storage on every change
+ if (typeof window !== 'undefined' && ref && ref.length > 0) {
+ window.localStorage.setItem(LOCAL_STORAGE_KEYS.LAST_SELECTED_SCHEMA(ref), schema)
+ }
+ }, [schema, ref])
return { selectedSchema: schema, setSelectedSchema }
}