Skip to content

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

(chore) studIo: Refactor use query state with select part 01 (#41819)

Joshen Lim32e1fedc79fd
diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecrets.tsx b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecrets.tsx
index 71387ce21f2..dc0c0c866ad 100644
--- a/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecrets.tsx
+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionSecrets/EdgeFunctionSecrets.tsx
@@ -1,6 +1,6 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { Search } from 'lucide-react'
-import { useRef, useState } from 'react'
+import { useEffect, useState } from 'react'
import { toast } from 'sonner'
import { useParams } from 'common'
@@ -9,7 +9,7 @@ import NoPermission from 'components/ui/NoPermission'
import { useSecretsDeleteMutation } from 'data/secrets/secrets-delete-mutation'
import { useSecretsQuery } from 'data/secrets/secrets-query'
import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { handleErrorOnDelete, useQueryStateWithSelect } from 'hooks/misc/useQueryStateWithSelect'
+import { parseAsString, useQueryState } from 'nuqs'
import { Badge, Card, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from 'ui'
import { Input } from 'ui-patterns/DataInputs/Input'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
@@ -22,9 +22,6 @@ export const EdgeFunctionSecrets = () => {
const { ref: projectRef } = useParams()
const [searchString, setSearchString] = useState('')
- // Track the ID being deleted to exclude it from error checking
- const deletingSecretNameRef = useRef<string | null>(null)
-
const { can: canReadSecrets, isLoading: isLoadingSecretsPermissions } = useAsyncCheckPermissions(
PermissionAction.FUNCTIONS_SECRET_READ,
'*'
@@ -32,7 +29,7 @@ export const EdgeFunctionSecrets = () => {
const { can: canUpdateSecrets } = useAsyncCheckPermissions(PermissionAction.SECRETS_WRITE, '*')
const {
- data,
+ data = [],
error,
isPending: isLoading,
isSuccess,
@@ -44,32 +41,26 @@ export const EdgeFunctionSecrets = () => {
{ enabled: canReadSecrets }
)
- const { setValue: setSelectedSecretToEdit, value: selectedSecretToEdit } =
- useQueryStateWithSelect({
- urlKey: 'edit',
- select: (secretName: string) =>
- secretName ? data?.find((secret) => secret.name === secretName) : undefined,
- enabled: !!data,
- onError: () => toast.error(`Secret not found`),
- })
-
- const { setValue: setSelectedSecretToDelete, value: selectedSecretToDelete } =
- useQueryStateWithSelect({
- urlKey: 'delete',
- select: (secretName: string) =>
- secretName ? data?.find((secret) => secret.name === secretName) : undefined,
- enabled: !!data,
- onError: (_error, selectedId) =>
- handleErrorOnDelete(deletingSecretNameRef, selectedId, `Secret not found`),
- })
-
- const { mutate: deleteSecret, isPending: isDeleting } = useSecretsDeleteMutation({
+ const [selectedIdToEdit, setSelectedIdToEdit] = useQueryState(
+ 'edit',
+ parseAsString.withOptions({ history: 'push', clearOnDefault: true })
+ )
+ const selectedSecretToEdit = data.find((secret) => secret.name === selectedIdToEdit)
+
+ const [selectedIdToDelete, setSelectedIdToDelete] = useQueryState(
+ 'delete',
+ parseAsString.withOptions({ history: 'push', clearOnDefault: true })
+ )
+ const selectedSecretToDelete = data.find((secret) => secret.name === selectedIdToDelete)
+
+ const {
+ mutate: deleteSecret,
+ isPending: isDeleting,
+ isSuccess: isSuccessDelete,
+ } = useSecretsDeleteMutation({
onSuccess: (_, variables) => {
toast.success(`Successfully deleted secret “${variables.secrets[0]}”`)
- setSelectedSecretToDelete(null)
- },
- onError: () => {
- deletingSecretNameRef.current = null
+ setSelectedIdToDelete(null)
},
})
@@ -90,6 +81,26 @@ export const EdgeFunctionSecrets = () => {
const showLoadingState = isLoadingSecretsPermissions || (canReadSecrets && isLoading)
+ useEffect(() => {
+ if (!!selectedIdToEdit && isSuccess && !selectedSecretToEdit) {
+ toast(`Secret ${selectedIdToEdit} cannot be found`)
+ setSelectedIdToEdit(null)
+ }
+ }, [isSuccess, selectedIdToEdit, selectedSecretToEdit, setSelectedIdToEdit])
+
+ useEffect(() => {
+ if (!!selectedIdToDelete && isSuccess && !selectedSecretToDelete && !isSuccessDelete) {
+ toast(`Secret ${selectedIdToDelete} cannot be found`)
+ setSelectedIdToDelete(null)
+ }
+ }, [
+ isSuccess,
+ isSuccessDelete,
+ selectedIdToDelete,
+ selectedSecretToDelete,
+ setSelectedIdToDelete,
+ ])
+
return (
<>
{showLoadingState ? (
@@ -119,7 +130,7 @@ export const EdgeFunctionSecrets = () => {
className="w-full md:w-80"
placeholder="Search for a secret"
value={searchString}
- onChange={(e: any) => setSearchString(e.target.value)}
+ onChange={(e) => setSearchString(e.target.value)}
icon={<Search />}
/>
</div>
@@ -135,8 +146,8 @@ export const EdgeFunctionSecrets = () => {
<EdgeFunctionSecret
key={secret.name}
secret={secret}
- onSelectEdit={() => setSelectedSecretToEdit(secret.name)}
- onSelectDelete={() => setSelectedSecretToDelete(secret.name)}
+ onSelectEdit={() => setSelectedIdToEdit(secret.name)}
+ onSelectDelete={() => setSelectedIdToDelete(secret.name)}
/>
))
) : secrets.length === 0 && searchString.length > 0 ? (
@@ -171,7 +182,7 @@ export const EdgeFunctionSecrets = () => {
<EditSecretSheet
secret={selectedSecretToEdit}
visible={!!selectedSecretToEdit}
- onClose={() => setSelectedSecretToEdit(null)}
+ onClose={() => setSelectedIdToEdit(null)}
/>
<ConfirmationModal
@@ -181,10 +192,9 @@ export const EdgeFunctionSecrets = () => {
confirmLabel="Delete secret"
confirmLabelLoading="Deleting secret"
title={`Delete secret “${selectedSecretToDelete?.name}”`}
- onCancel={() => setSelectedSecretToDelete(null)}
+ onCancel={() => setSelectedIdToDelete(null)}
onConfirm={() => {
if (selectedSecretToDelete) {
- deletingSecretNameRef.current = selectedSecretToDelete.name
deleteSecret({ projectRef, secrets: [selectedSecretToDelete.name] })
}
}}
diff --git a/apps/studio/components/interfaces/Storage/VectorBuckets/DeleteVectorTableModal.tsx b/apps/studio/components/interfaces/Storage/VectorBuckets/DeleteVectorTableModal.tsx
index 352fbcc6e20..c1677b0ce95 100644
--- a/apps/studio/components/interfaces/Storage/VectorBuckets/DeleteVectorTableModal.tsx
+++ b/apps/studio/components/interfaces/Storage/VectorBuckets/DeleteVectorTableModal.tsx
@@ -1,27 +1,31 @@
+import { parseAsString, useQueryState } from 'nuqs'
+import { useEffect } from 'react'
import { toast } from 'sonner'
import { useParams } from 'common'
import { useFDWDropForeignTableMutation } from 'data/fdw/fdw-drop-foreign-table-mutation'
import { useVectorBucketIndexDeleteMutation } from 'data/storage/vector-bucket-index-delete-mutation'
-import { VectorBucketIndex } from 'data/storage/vector-buckets-indexes-query'
+import { useVectorBucketsIndexesQuery } from 'data/storage/vector-buckets-indexes-query'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
+import { ConfirmationModal } from 'ui-patterns/Dialogs/ConfirmationModal'
import { useS3VectorsWrapperInstance } from './useS3VectorsWrapperInstance'
-interface DeleteVectorTableModalProps {
- visible: boolean
- table?: VectorBucketIndex
- onClose: () => void
-}
-
-export const DeleteVectorTableModal = ({
- visible,
- table,
- onClose,
-}: DeleteVectorTableModalProps) => {
- const { bucketId } = useParams()
+export const DeleteVectorTableModal = () => {
+ const { ref: projectRef, bucketId } = useParams()
const { data: project } = useSelectedProjectQuery()
+ const [selectedTableIdToDelete, setSelectedTableIdToDelete] = useQueryState(
+ 'deleteTable',
+ parseAsString.withOptions({ history: 'push', clearOnDefault: true })
+ )
+
+ const { data, isSuccess: isSuccessIndexes } = useVectorBucketsIndexesQuery({
+ projectRef,
+ vectorBucketName: bucketId,
+ })
+ const allIndexes = data?.indexes ?? []
+ const table = allIndexes.find((index) => index.indexName === selectedTableIdToDelete)
+
const { data: wrapperInstance } = useS3VectorsWrapperInstance({ bucketId })
const foreignTable = wrapperInstance?.tables?.find((x) => x.name === table?.indexName)
@@ -29,7 +33,11 @@ export const DeleteVectorTableModal = ({
onError: () => {},
})
- const { mutate: deleteIndex, isPending: isDeleting } = useVectorBucketIndexDeleteMutation({
+ const {
+ mutate: deleteIndex,
+ isPending: isDeleting,
+ isSuccess: isSuccessDelete,
+ } = useVectorBucketIndexDeleteMutation({
onSuccess: (_, vars) => {
try {
if (!!foreignTable) {
@@ -41,7 +49,7 @@ export const DeleteVectorTableModal = ({
})
}
toast.success(`Table "${vars.indexName}" deleted successfully`)
- onClose()
+ setSelectedTableIdToDelete(null)
} catch (error: any) {
toast.success(
`Table "${vars.indexName}" deleted successfully, but its corresponding foreign table failed to clean up: ${error.message}`
@@ -61,14 +69,27 @@ export const DeleteVectorTableModal = ({
})
}
+ useEffect(() => {
+ if (!!selectedTableIdToDelete && isSuccessIndexes && !table && !isSuccessDelete) {
+ toast(`Table ${selectedTableIdToDelete} cannot be found in your bucket`)
+ setSelectedTableIdToDelete(null)
+ }
+ }, [
+ isSuccessIndexes,
+ selectedTableIdToDelete,
+ table,
+ setSelectedTableIdToDelete,
+ isSuccessDelete,
+ ])
+
return (
<ConfirmationModal
- visible={visible}
+ visible={!!table}
loading={isDeleting}
variant="destructive"
title={`Confirm to delete table "${table?.indexName}"`}
onConfirm={onConfirmDelete}
- onCancel={onClose}
+ onCancel={() => setSelectedTableIdToDelete(null)}
>
{/* [Joshen] Can probably beef up more details here - what are potential side effects of deleting a table */}
<p className="text-sm">This action cannot be undone.</p>
diff --git a/apps/studio/components/interfaces/Storage/VectorBuckets/VectorBucketDetails/index.tsx b/apps/studio/components/interfaces/Storage/VectorBuckets/VectorBucketDetails/index.tsx
index 9388f689dfd..37a1df37147 100644
--- a/apps/studio/components/interfaces/Storage/VectorBuckets/VectorBucketDetails/index.tsx
+++ b/apps/studio/components/interfaces/Storage/VectorBuckets/VectorBucketDetails/index.tsx
@@ -1,8 +1,8 @@
import { MoreVertical, Search, Trash2 } from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/router'
-import { parseAsBoolean, useQueryState } from 'nuqs'
-import { useRef, useState } from 'react'
+import { parseAsBoolean, parseAsString, useQueryState } from 'nuqs'
+import { useState } from 'react'
import { useParams } from 'common'
import {
@@ -15,7 +15,6 @@ import {
import AlertError from 'components/ui/AlertError'
import { useVectorBucketQuery } from 'data/storage/vector-bucket-query'
import { useVectorBucketsIndexesQuery } from 'data/storage/vector-buckets-indexes-query'
-import { handleErrorOnDelete, useQueryStateWithSelect } from 'hooks/misc/useQueryStateWithSelect'
import { SqlEditor, TableEditor } from 'icons'
import {
Button,
@@ -54,14 +53,15 @@ export const VectorBucketDetails = () => {
const { ref: projectRef, bucketId } = useParams()
const { data: _bucket, isSuccess } = useSelectedVectorBucket()
- // Track the ID being deleted to exclude it from error checking
- const deletingTableIdRef = useRef<string | null>(null)
-
const [filterString, setFilterString] = useState('')
const [showDeleteModal, setShowDeleteModal] = useQueryState(
'delete',
parseAsBoolean.withDefault(false).withOptions({ history: 'push', clearOnDefault: true })
)
+ const [_, setSelectedTableIdToDelete] = useQueryState(
+ 'deleteTable',
+ parseAsString.withOptions({ history: 'push', clearOnDefault: true })
+ )
const {
data: bucket,
@@ -73,21 +73,16 @@ export const VectorBucketDetails = () => {
{ enabled: isSuccess && !!_bucket }
)
- const { data, isPending: isLoadingIndexes } = useVectorBucketsIndexesQuery({
+ const {
+ data,
+ isPending: isLoadingIndexes,
+ isSuccess: isSuccessIndexes,
+ } = useVectorBucketsIndexesQuery({
projectRef,
vectorBucketName: bucket?.vectorBucketName,
})
const allIndexes = data?.indexes ?? []
- const { setValue: setSelectedTableToDelete, value: selectedTableToDelete } =
- useQueryStateWithSelect({
- urlKey: 'deleteTable',
- select: (id: string) => (id ? allIndexes.find((index) => index.indexName === id) : undefined),
- enabled: !!allIndexes.length,
- onError: (_error, selectedId) =>
- handleErrorOnDelete(deletingTableIdRef, selectedId, `Table not found`),
- })
-
const filteredList =
filterString.length === 0
? allIndexes
@@ -280,7 +275,7 @@ export const VectorBucketDetails = () => {
className="flex items-center space-x-2"
onClick={(e) => {
e.stopPropagation()
- setSelectedTableToDelete(index.indexName)
+ setSelectedTableIdToDelete(index.indexName)
}}
>
<Trash2 size={12} className="text-foreground-lighter" />
@@ -326,11 +321,7 @@ export const VectorBucketDetails = () => {
</ScaffoldContainer>
)}
- <DeleteVectorTableModal
- visible={!!selectedTableToDelete}
- table={selectedTableToDelete}
- onClose={() => setSelectedTableToDelete(null)}
- />
+ <DeleteVectorTableModal />
<DeleteVectorBucketModal
visible={showDeleteModal}
diff --git a/apps/studio/components/ui/SchemaSelector.tsx b/apps/studio/components/ui/SchemaSelector.tsx
index 58626dc3d40..bed2b22caef 100644
--- a/apps/studio/components/ui/SchemaSelector.tsx
+++ b/apps/studio/components/ui/SchemaSelector.tsx
@@ -38,7 +38,7 @@ interface SchemaSelectorProps {
align?: 'start' | 'end'
}
-const SchemaSelector = ({
+export const SchemaSelector = ({
className,
disabled = false,
size = 'tiny',
diff --git a/apps/studio/pages/project/[ref]/auth/policies.tsx b/apps/studio/pages/project/[ref]/auth/policies.tsx
index 6210cb4a36d..5a5b148adb1 100644
--- a/apps/studio/pages/project/[ref]/auth/policies.tsx
+++ b/apps/studio/pages/project/[ref]/auth/policies.tsx
@@ -13,7 +13,7 @@ import { getGeneralPolicyTemplates } from 'components/interfaces/Auth/Policies/P
import { PolicyEditorPanel } from 'components/interfaces/Auth/Policies/PolicyEditorPanel'
import { generatePolicyUpdateSQL } from 'components/interfaces/Auth/Policies/PolicyTableRow/PolicyTableRow.utils'
import AuthLayout from 'components/layouts/AuthLayout/AuthLayout'
-import DefaultLayout from 'components/layouts/DefaultLayout'
+import { DefaultLayout } from 'components/layouts/DefaultLayout'
import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
import AlertError from 'components/ui/AlertError'
import { BannerRlsEventTrigger } from 'components/ui/BannerStack/Banners/BannerRlsEventTrigger'
@@ -21,13 +21,12 @@ import { BannerStack } from 'components/ui/BannerStack/BannerStack'
import { BannerStackProvider, useBannerStack } from 'components/ui/BannerStack/BannerStackProvider'
import { DocsButton } from 'components/ui/DocsButton'
import NoPermission from 'components/ui/NoPermission'
-import SchemaSelector from 'components/ui/SchemaSelector'
+import { SchemaSelector } from 'components/ui/SchemaSelector'
import { useProjectPostgrestConfigQuery } from 'data/config/project-postgrest-config-query'
import { useDatabasePoliciesQuery } from 'data/database-policies/database-policies-query'
import { useTablesQuery } from 'data/tables/tables-query'
import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
-import { useQueryStateWithSelect } from 'hooks/misc/useQueryStateWithSelect'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { useIsProtectedSchema } from 'hooks/useProtectedSchemas'
import { DOCS_URL } from 'lib/constants'
@@ -102,6 +101,12 @@ const AuthPoliciesPage: NextPageWithLayout = () => {
parseAsString.withDefault('').withOptions({ history: 'replace', clearOnDefault: true })
)
const deferredSearchString = useDeferredValue(searchString)
+
+ const [selectedIdToEdit, setSelectedIdToEdit] = useQueryState(
+ 'edit',
+ parseAsString.withOptions({ history: 'push', clearOnDefault: true })
+ )
+
const { ref: projectRef } = useParams()
const { data: project } = useSelectedProjectQuery()
const { data: postgrestConfig } = useProjectPostgrestConfigQuery({ projectRef: project?.ref })
@@ -128,23 +133,16 @@ const AuthPoliciesPage: NextPageWithLayout = () => {
)
const {
- data: policies,
+ data: policies = [],
isPending: isLoadingPolicies,
isError: isPoliciesError,
+ isSuccess: isPoliciesSuccess,
error: policiesError,
} = useDatabasePoliciesQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
})
-
- const { setValue: setSelectedPolicyIdToEdit, value: selectedPolicyIdToEdit } =
- useQueryStateWithSelect({
- urlKey: 'edit',
- select: (id: string) =>
- id ? policies?.find((policy) => policy.id.toString() === id) : undefined,
- enabled: !!policies,
- onError: () => toast.error(`Policy not found`),
- })
+ const selectedPolicyToEdit = policies.find((policy) => policy.id.toString() === selectedIdToEdit)
const {
data: tables,
@@ -179,7 +177,7 @@ const AuthPoliciesPage: NextPageWithLayout = () => {
const handleSelectCreatePolicy = useCallback(
(table: string) => {
setSelectedTable(table)
- setSelectedPolicyIdToEdit(null)
+ setSelectedIdToEdit(null)
setShowCreatePolicy(true)
if (isInlineEditorEnabled) {
@@ -219,7 +217,7 @@ const AuthPoliciesPage: NextPageWithLayout = () => {
setEditorPanelTemplates(templates)
openSidebar(SIDEBAR_KEYS.EDITOR_PANEL)
} else {
- setSelectedPolicyIdToEdit(policy.id.toString())
+ setSelectedIdToEdit(policy.id.toString())
}
},
[isInlineEditorEnabled, openSidebar]
@@ -252,7 +250,14 @@ const AuthPoliciesPage: NextPageWithLayout = () => {
isRlsBannerDismissed,
])
- const isUpdatingPolicy = !!selectedPolicyIdToEdit
+ useEffect(() => {
+ if (selectedIdToEdit && isPoliciesSuccess && !selectedPolicyToEdit) {
+ toast(`Policy ID ${selectedIdToEdit} cannot be found`)
+ setSelectedIdToEdit(null)
+ }
+ }, [selectedIdToEdit, selectedPolicyToEdit, isPoliciesSuccess, setSelectedIdToEdit])
+
+ const isUpdatingPolicy = !!selectedIdToEdit
if (isPermissionsLoaded && !canReadPolicies) {
return <NoPermission isFullPage resourceText="view this project's RLS policies" />
@@ -340,15 +345,15 @@ const AuthPoliciesPage: NextPageWithLayout = () => {
)}
<PolicyEditorPanel
- visible={showCreatePolicy || isUpdatingPolicy}
+ visible={showCreatePolicy || (isUpdatingPolicy && !!selectedPolicyToEdit)}
schema={schema}
searchString={searchString}
selectedTable={isUpdatingPolicy ? undefined : selectedTable}
- selectedPolicy={isUpdatingPolicy ? selectedPolicyIdToEdit : undefined}
+ selectedPolicy={isUpdatingPolicy ? selectedPolicyToEdit : undefined}
onSelectCancel={() => {
setSelectedTable(undefined)
if (isUpdatingPolicy) {
- setSelectedPolicyIdToEdit(null)
+ setSelectedIdToEdit(null)
} else {
setShowCreatePolicy(false)
}