From 24f590e893f3e25a4bb8652be66268ac81b9c61d Mon Sep 17 00:00:00 2001 From: Ivan Vasilov Date: Mon, 2 Sep 2024 09:15:37 +0200 Subject: [PATCH] fix: Fix the caching of the selected schema (#28999) * Cache the original schema and ignore the schema changes in the local storage. This is to avoid unwanted changes in the UI. * Nit refactor to ensure immutability --------- Co-authored-by: Joshen Lim --- apps/studio/hooks/misc/useSchemaQueryState.ts | 25 +++++++++++-------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/apps/studio/hooks/misc/useSchemaQueryState.ts b/apps/studio/hooks/misc/useSchemaQueryState.ts index 22313eedf31de..b0e183c6bd24c 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 } }