The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: Clean `onSuccess` and `onError` props on `useQuery` (#40641)
Ivan Vasilova40ccc4b4538
diff --git a/apps/studio/components/interfaces/Database/RestoreToNewProject/RestoreToNewProject.tsx b/apps/studio/components/interfaces/Database/RestoreToNewProject/RestoreToNewProject.tsxindex 7f3d0363c01..a04ce4010d2 100644--- a/apps/studio/components/interfaces/Database/RestoreToNewProject/RestoreToNewProject.tsx+++ b/apps/studio/components/interfaces/Database/RestoreToNewProject/RestoreToNewProject.tsx@@ -1,7 +1,7 @@import { PermissionAction } from '@supabase/shared-types/out/constants'import { Loader2 } from 'lucide-react'import Link from 'next/link'-import { useState } from 'react'+import { useEffect, useState } from 'react'import { PITRForm } from 'components/interfaces/Database/Backups/PITR/PITRForm'import { BackupsList } from 'components/interfaces/Database/Backups/RestoreToNewProject/BackupsList'@@ -28,7 +28,7 @@ import {import { DOCS_URL, PROJECT_STATUS } from 'lib/constants'import { getDatabaseMajorVersion } from 'lib/helpers'import { Alert_Shadcn_, AlertDescription_Shadcn_, AlertTitle_Shadcn_, Button } from 'ui'-import { Admonition } from 'ui-patterns'+import { Admonition } from 'ui-patterns/admonition'import { PreviousRestoreItem } from './PreviousRestoreItem'export const RestoreToNewProject = () => {@@ -75,6 +75,7 @@ export const RestoreToNewProject = () => {data: cloneStatus,refetch: refetchCloneStatus,isLoading: cloneStatusLoading,+ isSuccess: isCloneStatusSuccess,} = useCloneStatusQuery({projectRef: project?.ref,@@ -82,16 +83,20 @@ export const RestoreToNewProject = () => {{refetchInterval,refetchOnWindowFocus: false,- onSuccess: (data) => {- const hasTransientState = data?.clones.some((c) => c.status === 'IN_PROGRESS')- if (!hasTransientState) setRefetchInterval(false)- },enabled: PHYSICAL_BACKUPS_ENABLED || PITR_ENABLED,})const IS_CLONED_PROJECT = cloneStatus?.cloned_from?.source_project?.ref ? true : falseconst isLoading = !isPermissionsLoaded || cloneBackupsLoading || cloneStatusLoading+ useEffect(() => {+ if (!isCloneStatusSuccess) return+ const hasTransientState = cloneStatus.clones.some((c) => c.status === 'IN_PROGRESS')+ if (!hasTransientState) {+ setRefetchInterval(false)+ }+ }, [cloneStatus?.clones, isCloneStatusSuccess])+const previousClones = cloneStatus?.clonesconst isRestoring = previousClones?.some((c) => c.status === 'IN_PROGRESS')const restoringClone = previousClones?.find((c) => c.status === 'IN_PROGRESS')diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagementForm.tsx b/apps/studio/components/interfaces/DiskManagement/DiskManagementForm.tsxindex b86b291ce53..5ff32c1e12f 100644--- a/apps/studio/components/interfaces/DiskManagement/DiskManagementForm.tsx+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagementForm.tsx@@ -24,6 +24,7 @@ import { useProjectAddonUpdateMutation } from 'data/subscriptions/project-addon-import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'import { AddonVariantId } from 'data/subscriptions/types'import { useResourceWarningsQuery } from 'data/usage/resource-warnings-query'+import { useCheckEntitlements } from 'hooks/misc/useCheckEntitlements'import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'import {@@ -64,7 +65,6 @@ import {} from './ui/DiskManagement.constants'import { NoticeBar } from './ui/NoticeBar'import { SpendCapDisabledSection } from './ui/SpendCapDisabledSection'-import { useCheckEntitlements } from 'hooks/misc/useCheckEntitlements'export function DiskManagementForm() {const { ref: projectRef } = useParams()@@ -104,29 +104,10 @@ export function DiskManagementForm() {{refetchInterval,refetchOnWindowFocus: false,- onSuccess: (data) => {- // @ts-ignore- const { type, iops, throughput_mbps, size_gb } = data?.attributes ?? { size_gb: 0 }- const formValues = {- storageType: type,- provisionedIOPS: iops,- throughput: throughput_mbps,- totalSize: size_gb,- }-- if (!('requested_modification' in data)) {- if (refetchInterval !== false) {- form.reset(formValues)- setRefetchInterval(false)- toast.success('Disk configuration changes have been successfully applied!')- }- } else {- setRefetchInterval(2000)- }- },enabled: project != null && isAws,})+const { isSuccess: isAddonsSuccess } = useProjectAddonsQuery({ projectRef })const { isWithinCooldownWindow, isSuccess: isCooldownSuccess } =useRemainingDurationForDiskAttributeUpdate({@@ -173,6 +154,28 @@ export function DiskManagementForm() {reValidateMode: 'onChange',})+ useEffect(() => {+ if (!isDiskAttributesSuccess) return+ // @ts-ignore+ const { type, iops, throughput_mbps, size_gb } = data?.attributes ?? { size_gb: 0 }+ const formValues = {+ storageType: type,+ provisionedIOPS: iops,+ throughput: throughput_mbps,+ totalSize: size_gb,+ }++ if (!('requested_modification' in data)) {+ if (refetchInterval !== false) {+ form.reset(formValues)+ setRefetchInterval(false)+ toast.success('Disk configuration changes have been successfully applied!')+ }+ } else {+ setRefetchInterval(2000)+ }+ }, [data, isDiskAttributesSuccess, form, refetchInterval])+const { computeSize: modifiedComputeSize } = form.watch()// We only support disk configurations for >=Large instancesdiff --git a/apps/studio/components/interfaces/Home/ServiceStatus.tsx b/apps/studio/components/interfaces/Home/ServiceStatus.tsxindex a0c6dc343e4..95226b175ed 100644--- a/apps/studio/components/interfaces/Home/ServiceStatus.tsx+++ b/apps/studio/components/interfaces/Home/ServiceStatus.tsx@@ -123,7 +123,9 @@ export const ServiceStatus = () => {projectRef: ref,},{- refetchInterval: (data) => (data?.some((service) => !service.healthy) ? 5000 : false),+ refetchInterval: (data) => {+ return data?.some((service) => !service.healthy) ? 5000 : false+ },})const { data: edgeFunctionsStatus, refetch: refetchEdgeFunctionServiceStatus } =@@ -132,7 +134,9 @@ export const ServiceStatus = () => {projectRef: ref,},{- refetchInterval: (data) => (!data?.healthy ? 5000 : false),+ refetchInterval: (data) => {+ return !data?.healthy ? 5000 : false+ },})diff --git a/apps/studio/components/interfaces/HomeNew/ServiceStatus.tsx b/apps/studio/components/interfaces/HomeNew/ServiceStatus.tsxindex 23d77e00f57..62278cfabeb 100644--- a/apps/studio/components/interfaces/HomeNew/ServiceStatus.tsx+++ b/apps/studio/components/interfaces/HomeNew/ServiceStatus.tsx@@ -109,7 +109,11 @@ export const ServiceStatus = () => {// [Joshen] Need pooler service check eventuallyconst { data: status, isLoading } = useProjectServiceStatusQuery({ projectRef: ref },- { refetchInterval: (data) => (data?.some((service) => !service.healthy) ? 5000 : false) }+ {+ refetchInterval: (data) => {+ return data?.some((service) => !service.healthy) ? 5000 : false+ },+ })const { data: edgeFunctionsStatus } = useEdgeFunctionServiceStatusQuery({ projectRef: ref },diff --git a/apps/studio/components/interfaces/Reports/ReportBlock/ReportBlock.tsx b/apps/studio/components/interfaces/Reports/ReportBlock/ReportBlock.tsxindex e70d6e2ae36..cd2f16e973a 100644--- a/apps/studio/components/interfaces/Reports/ReportBlock/ReportBlock.tsx+++ b/apps/studio/components/interfaces/Reports/ReportBlock/ReportBlock.tsx@@ -1,5 +1,5 @@import { X } from 'lucide-react'-import { useCallback, useState } from 'react'+import { useCallback, useEffect, useState } from 'react'import { toast } from 'sonner'import { useParams } from 'common'@@ -49,7 +49,7 @@ export const ReportBlock = ({const isSnippet = item.attribute.startsWith('snippet_')- const { data, error, isLoading } = useContentIdQuery(+ const { data, error, isLoading, isSuccess } = useContentIdQuery({ projectRef, id: item.id },{enabled: isSnippet && !!item.id,@@ -60,13 +60,9 @@ export const ReportBlock = ({if (failureCount >= 2) return falsereturn true},- onSuccess: (contentData) => {- if (!isSnippet) return- const fetchedSql = (contentData?.content as SqlSnippets.Content | undefined)?.sql- if (fetchedSql) runQuery('select', fetchedSql)- },})+const sql = isSnippet ? (data?.content as SqlSnippets.Content)?.sql : undefinedconst chartConfig = { ...DEFAULT_CHART_CONFIG, ...(item.chartConfig ?? {}) }const isDeprecatedChart = DEPRECATED_REPORTS.includes(item.attribute)@@ -131,6 +127,15 @@ export const ReportBlock = ({[projectRef, readOnlyConnectionString, postgresConnectionString, executeSql])+ useEffect(() => {+ if (!isSuccess) return+ if (!isSnippet) return+ const fetchedSql = (data?.content as SqlSnippets.Content | undefined)?.sql+ if (fetchedSql) {+ runQuery('select', fetchedSql)+ }+ }, [data, isSuccess, runQuery, isSnippet])+const sqlHasChanged = useChangedSync(sql)const isRefreshingChanged = useChangedSync(isRefreshing)if (sqlHasChanged || (isRefreshingChanged && isRefreshing)) {diff --git a/apps/studio/components/interfaces/Reports/SharedAPIReport/SharedAPIReport.constants.ts b/apps/studio/components/interfaces/Reports/SharedAPIReport/SharedAPIReport.constants.tsindex 768925edf86..2684c59b569 100644--- a/apps/studio/components/interfaces/Reports/SharedAPIReport/SharedAPIReport.constants.ts+++ b/apps/studio/components/interfaces/Reports/SharedAPIReport/SharedAPIReport.constants.ts@@ -1,11 +1,12 @@-import { get } from 'data/fetchers'-import { generateRegexpWhere } from '../Reports.constants'-import { ReportFilterItem } from '../Reports.types'-import { useQueries, useQueryClient } from '@tanstack/react-query'import * as Sentry from '@sentry/nextjs'+import { useQueries, useQueryClient } from '@tanstack/react-query'+import { isEqual } from 'lodash'import { useState } from 'react'+import { useParams } from 'common'-import { isEqual } from 'lodash'+import { get } from 'data/fetchers'+import { generateRegexpWhere } from '../Reports.constants'+import { ReportFilterItem } from '../Reports.types'export const SHARED_API_REPORT_SQL = {totalRequests: {@@ -303,7 +304,7 @@ export const useSharedAPIReport = ({const error = keys.reduce((acc, key, i) => {- acc[key] = queries[i].error as string+ acc[key] = queries[i].error as unknown as stringreturn acc},{} as { [K in keyof typeof SHARED_API_REPORT_SQL]: string }diff --git a/apps/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainConfig.tsx b/apps/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainConfig.tsxindex 5c1078f72e6..a3b2c3d553e 100644--- a/apps/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainConfig.tsx+++ b/apps/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainConfig.tsx@@ -39,7 +39,7 @@ export const CustomDomainConfig = () => {} = useCustomDomainsQuery({ projectRef: ref },{- refetchInterval(data) {+ refetchInterval: (data) => {// while setting up the ssl certificate, we want to poll every 5 secondsif (data?.customDomain?.ssl.status) {return 10000 // 10 secondsdiff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DeployNewReplicaPanel.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DeployNewReplicaPanel.tsxindex 3d975a76961..a17cc594e58 100644--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DeployNewReplicaPanel.tsx+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DeployNewReplicaPanel.tsx@@ -125,7 +125,7 @@ const DeployNewReplicaPanel = ({const [selectedRegion, setSelectedRegion] = useState<string>(defaultRegion)const [selectedCompute, setSelectedCompute] = useState(defaultCompute)- useProjectDetailQuery(+ const { data: projectDetail, isSuccess: isProjectDetailSuccess } = useProjectDetailQuery({ ref: projectRef },{refetchInterval,@@ -136,6 +136,13 @@ const DeployNewReplicaPanel = ({})+ useEffect(() => {+ if (!isProjectDetailSuccess) return+ if (projectDetail.is_physical_backups_enabled) {+ setRefetchInterval(false)+ }+ }, [projectDetail?.is_physical_backups_enabled, isProjectDetailSuccess])+const { mutate: enablePhysicalBackups, isLoading: isEnabling } = useEnablePhysicalBackupsMutation({onSuccess: () => {diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsxindex 336708e6085..579c84cf363 100644--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx@@ -3,7 +3,7 @@ import { partition } from 'lodash'import { ChevronDown, Globe2, Loader2, Network } from 'lucide-react'import { useTheme } from 'next-themes'import Link from 'next/link'-import { useEffect, useMemo, useRef, useState } from 'react'+import { useEffect, useMemo, useState } from 'react'import ReactFlow, { Background, Edge, ReactFlowProvider, useReactFlow } from 'reactflow'import 'reactflow/dist/style.css'@@ -54,8 +54,7 @@ const InstanceConfigurationUI = ({ diagramOnly = false }: InstanceConfigurationUconst isOrioleDb = useIsOrioleDb()const { resolvedTheme } = useTheme()const { ref: projectRef } = useParams()- const numTransition = useRef<number>()- const { data: project, isLoading: isLoadingProject } = useSelectedProjectQuery()+ const { isLoading: isLoadingProject } = useSelectedProjectQuery()const isAws = useIsAwsCloudProvider()const { infrastructureReadReplicas } = useIsFeatureEnabled(['infrastructure:read_replicas'])@@ -63,7 +62,7 @@ const InstanceConfigurationUI = ({ diagramOnly = false }: InstanceConfigurationUconst [view, setView] = useState<'flow' | 'map'>('flow')const [showDeleteAllModal, setShowDeleteAllModal] = useState(false)const { showNewReplicaPanel, setShowNewReplicaPanel } = useShowNewReplicaPanel()- const [refetchInterval, setRefetchInterval] = useState<number | boolean>(10000)+ const [refetchInterval, setRefetchInterval] = useState<number | false>(10000)const [newReplicaRegion, setNewReplicaRegion] = useState<AWS_REGIONS_KEYS>()const [selectedReplicaToDrop, setSelectedReplicaToDrop] = useState<Database>()const [selectedReplicaToRestart, setSelectedReplicaToRestart] = useState<Database>()@@ -74,9 +73,7 @@ const InstanceConfigurationUI = ({ diagramOnly = false }: InstanceConfigurationUdata: loadBalancers,refetch: refetchLoadBalancers,isSuccess: isSuccessLoadBalancers,- } = useLoadBalancersQuery({- projectRef,- })+ } = useLoadBalancersQuery({ projectRef })const {data,error,@@ -84,50 +81,57 @@ const InstanceConfigurationUI = ({ diagramOnly = false }: InstanceConfigurationUisLoading,isError,isSuccess: isSuccessReplicas,- } = useReadReplicasQuery({- projectRef,- })+ } = useReadReplicasQuery({ projectRef })const [[primary], replicas] = useMemo(() => partition(data ?? [], (db) => db.identifier === projectRef),[data, projectRef])- useReadReplicasStatusesQuery(- { projectRef },- {- refetchInterval: refetchInterval as any,- refetchOnWindowFocus: false,- onSuccess: async (res) => {- const fixedStatues = [- REPLICA_STATUS.ACTIVE_HEALTHY,- REPLICA_STATUS.ACTIVE_UNHEALTHY,- REPLICA_STATUS.INIT_READ_REPLICA_FAILED,- ]- const replicasInTransition = res.filter((db) => {- const { status } = db.replicaInitializationStatus || {}- return (- !fixedStatues.includes(db.status) || status === ReplicaInitializationStatus.InProgress- )- })- const hasTransientStatus = replicasInTransition.length > 0+ const { data: replicasStatuses, isSuccess: isSuccessReplicasStatuses } =+ useReadReplicasStatusesQuery(+ { projectRef },+ {+ refetchInterval: refetchInterval,+ refetchOnWindowFocus: false,+ }+ )- // If any replica's status has changed, refetch databases- if (- numTransition.current !== replicasInTransition.length ||- res.length !== (data ?? []).length- ) {- numTransition.current = replicasInTransition.length- await refetchReplicas()- setTimeout(() => refetchLoadBalancers(), 2000)- }+ const numReplicas = useMemo(() => data?.length ?? 0, [data])+ useEffect(() => {+ if (!isSuccessReplicasStatuses) return+ const refetch = async () => {+ const fixedStatues = [+ REPLICA_STATUS.ACTIVE_HEALTHY,+ REPLICA_STATUS.ACTIVE_UNHEALTHY,+ REPLICA_STATUS.INIT_READ_REPLICA_FAILED,+ ]+ const replicasInTransition = replicasStatuses.filter((db) => {+ const { status } = db.replicaInitializationStatus || {}+ return (+ !fixedStatues.includes(db.status) || status === ReplicaInitializationStatus.InProgress+ )+ })+ const hasTransientStatus = replicasInTransition.length > 0++ // If any replica's status has changed, refetch databases+ if (replicasStatuses.length !== numReplicas) {+ await refetchReplicas()+ setTimeout(() => refetchLoadBalancers(), 2000)+ }- // If all replicas are active healthy, stop fetching statuses- if (!hasTransientStatus) {- setRefetchInterval(false)- }- },+ // If all replicas are active healthy, stop fetching statuses+ if (!hasTransientStatus) {+ setRefetchInterval(false)+ }}- )+ refetch()+ }, [+ numReplicas,+ isSuccessReplicasStatuses,+ refetchLoadBalancers,+ refetchReplicas,+ replicasStatuses,+ ])const backgroundPatternColor =resolvedTheme === 'dark' ? 'rgba(255, 255, 255, 0.3)' : 'rgba(0, 0, 0, 0.4)'diff --git a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceWithTables/index.tsx b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceWithTables/index.tsxindex ac3cb172101..41f4eee9ad7 100644--- a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceWithTables/index.tsx+++ b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/NamespaceWithTables/index.tsx@@ -72,7 +72,8 @@ export const NamespaceWithTables = ({projectRef,},{- refetchInterval: (data = []) => {+ refetchInterval: (_data) => {+ const data = _data ?? []if (pollIntervalNamespaceTables === 0) return falseconst publicationTables = publication?.tables ?? []diff --git a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/index.tsx b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/index.tsxindex f5aa488a70c..5bac33e4abe 100644--- a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/index.tsx+++ b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/index.tsx@@ -122,7 +122,8 @@ export const AnalyticBucketDetails = () => {warehouse: wrapperValues.warehouse,},{- refetchInterval: (data = []) => {+ refetchInterval: (_data) => {+ const data = _data ?? []if (pollIntervalNamespaces === 0) return falseconst publicationTableSchemas = publication?.tables.map((x) => x.schema) ?? []diff --git a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/useAnalyticsBucketWrapperInstance.tsx b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/useAnalyticsBucketWrapperInstance.tsxindex 795b2b81011..904aff48796 100644--- a/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/useAnalyticsBucketWrapperInstance.tsx+++ b/apps/studio/components/interfaces/Storage/AnalyticsBuckets/AnalyticsBucketDetails/useAnalyticsBucketWrapperInstance.tsx@@ -5,13 +5,13 @@ import {getWrapperMetaForWrapper,wrapperMetaComparator,} from 'components/interfaces/Integrations/Wrappers/Wrappers.utils'-import { type FDW, useFDWsQuery } from 'data/fdw/fdws-query'+import { useFDWsQuery } from 'data/fdw/fdws-query'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { getAnalyticsBucketFDWName } from './AnalyticsBucketDetails.utils'export const useAnalyticsBucketWrapperInstance = ({ bucketId }: { bucketId?: string },- options?: { enabled?: boolean; refetchInterval?: (data: FDW[] | undefined) => number | false }+ options?: { enabled?: boolean }) => {const { data: project, isLoading: isLoadingProject } = useSelectedProjectQuery()@@ -21,11 +21,7 @@ export const useAnalyticsBucketWrapperInstance = (projectRef: project?.ref,connectionString: project?.connectionString,},- {- enabled: defaultEnabled && !!bucketId,- refetchInterval: (data) =>- !!options?.refetchInterval ? options.refetchInterval(data) : false,- }+ { enabled: defaultEnabled && !!bucketId })const icebergWrapper = useMemo(() => {diff --git a/apps/studio/components/interfaces/Storage/VectorBuckets/useS3VectorsWrapperInstance.tsx b/apps/studio/components/interfaces/Storage/VectorBuckets/useS3VectorsWrapperInstance.tsxindex ad110ddc018..6de07856474 100644--- a/apps/studio/components/interfaces/Storage/VectorBuckets/useS3VectorsWrapperInstance.tsx+++ b/apps/studio/components/interfaces/Storage/VectorBuckets/useS3VectorsWrapperInstance.tsx@@ -5,26 +5,20 @@ import {WRAPPERS,} from 'components/interfaces/Integrations/Wrappers/Wrappers.constants'import { wrapperMetaComparator } from 'components/interfaces/Integrations/Wrappers/Wrappers.utils'-import { type FDW, useFDWsQuery } from 'data/fdw/fdws-query'+import { useFDWsQuery } from 'data/fdw/fdws-query'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { getVectorBucketFDWName } from './VectorBuckets.utils'-export const useS3VectorsWrapperInstance = (- { bucketId }: { bucketId?: string },- options?: { enabled?: boolean; refetchInterval?: (data: FDW[] | undefined) => number | false }-) => {+export const useS3VectorsWrapperInstance = ({ bucketId }: { bucketId?: string }) => {const { data: project, isLoading: isLoadingProject } = useSelectedProjectQuery()- const defaultEnabled = options?.enabled ?? trueconst { data, isLoading: isLoadingFDWs } = useFDWsQuery({projectRef: project?.ref,connectionString: project?.connectionString,},{- enabled: defaultEnabled && !!bucketId,- refetchInterval: (data) =>- !!options?.refetchInterval ? options.refetchInterval(data) : false,+ enabled: !!bucketId,})diff --git a/apps/studio/components/layouts/ProjectLayout/BuildingState.tsx b/apps/studio/components/layouts/ProjectLayout/BuildingState.tsxindex 5093a6af9b3..b370556cea5 100644--- a/apps/studio/components/layouts/ProjectLayout/BuildingState.tsx+++ b/apps/studio/components/layouts/ProjectLayout/BuildingState.tsx@@ -1,5 +1,6 @@import { ArrowRight, Loader2 } from 'lucide-react'import Link from 'next/link'+import { useEffect } from 'react'import { useParams } from 'common'import { ClientLibrary } from 'components/interfaces/Home/ClientLibrary'@@ -30,22 +31,32 @@ const BuildingState = () => {'project_homepage:client_libraries',])- useProjectStatusQuery(+ const { data: projectStatusData, isSuccess: isProjectStatusSuccess } = useProjectStatusQuery({ projectRef: ref },{enabled: project?.status !== PROJECT_STATUS.ACTIVE_HEALTHY,- refetchInterval: (res) => {- return res?.status === PROJECT_STATUS.ACTIVE_HEALTHY ? false : 4000- },- onSuccess: async (res) => {- if (res.status === PROJECT_STATUS.ACTIVE_HEALTHY) {- if (ref) await invalidateProjectDetailsQuery(ref)- await invalidateProjectsQuery()- }+ refetchInterval: (data) => {+ return data?.status === PROJECT_STATUS.ACTIVE_HEALTHY ? false : 4000},})+ useEffect(() => {+ if (!isProjectStatusSuccess) return+ if (projectStatusData?.status === PROJECT_STATUS.ACTIVE_HEALTHY) {+ if (ref) {+ invalidateProjectDetailsQuery(ref)+ }+ invalidateProjectsQuery()+ }+ }, [+ isProjectStatusSuccess,+ projectStatusData,+ ref,+ invalidateProjectDetailsQuery,+ invalidateProjectsQuery,+ ])+if (project === undefined) return nullreturn (diff --git a/apps/studio/components/layouts/ProjectLayout/PausedState/PauseDisabledState.tsx b/apps/studio/components/layouts/ProjectLayout/PausedState/PauseDisabledState.tsxindex 965f16e0678..51e89c816db 100644--- a/apps/studio/components/layouts/ProjectLayout/PausedState/PauseDisabledState.tsx+++ b/apps/studio/components/layouts/ProjectLayout/PausedState/PauseDisabledState.tsx@@ -1,5 +1,5 @@import { ChevronDown, Download, ExternalLink } from 'lucide-react'-import { useState } from 'react'+import { useEffect, useState } from 'react'import { toast } from 'sonner'import { useParams } from 'common'@@ -35,21 +35,24 @@ export const PauseDisabledState = () => {)const latestBackup = pauseStatus?.latest_downloadable_backup_id- const { data: storageArchive } = useStorageArchiveQuery(+ const { data: storageArchive, isSuccess: isStorageArchiveSuccess } = useStorageArchiveQuery({ projectRef: ref },{refetchInterval,refetchOnWindowFocus: false,- onSuccess: (data) => {- if (data.fileUrl && refetchInterval !== false) {- toast.success('Downloading storage objects', { id: toastId })- setToastId(undefined)- setRefetchInterval(false)- downloadStorageArchive(data.fileUrl)- }- },})++ useEffect(() => {+ if (!isStorageArchiveSuccess) return+ if (storageArchive.fileUrl && refetchInterval !== false) {+ toast.success('Downloading storage objects', { id: toastId })+ setToastId(undefined)+ setRefetchInterval(false)+ downloadStorageArchive(storageArchive.fileUrl)+ }+ }, [isStorageArchiveSuccess, storageArchive, refetchInterval])+const storageArchiveUrl = storageArchive?.fileUrlconst { mutate: downloadBackup } = useBackupDownloadMutation({diff --git a/apps/studio/components/layouts/ProjectLayout/PausingState.tsx b/apps/studio/components/layouts/ProjectLayout/PausingState.tsxindex 8da3e98a855..07509eb308f 100644--- a/apps/studio/components/layouts/ProjectLayout/PausingState.tsx+++ b/apps/studio/components/layouts/ProjectLayout/PausingState.tsx@@ -19,22 +19,32 @@ const PausingState = ({ project }: PausingStateProps) => {const { invalidateProjectsQuery } = useInvalidateProjectsInfiniteQuery()const { invalidateProjectDetailsQuery } = useInvalidateProjectDetailsQuery()- useProjectStatusQuery(+ const { data: projectStatusData, isSuccess: isProjectStatusSuccess } = useProjectStatusQuery({ projectRef: ref },{enabled: startPolling,- refetchInterval: (res) => {- return res?.status === PROJECT_STATUS.INACTIVE ? false : 2000- },- onSuccess: async (res) => {- if (res.status === PROJECT_STATUS.INACTIVE) {- if (ref) await invalidateProjectDetailsQuery(ref)- await invalidateProjectsQuery()- }+ refetchInterval: (data) => {+ return data?.status === PROJECT_STATUS.INACTIVE ? false : 2000},})+ useEffect(() => {+ if (!isProjectStatusSuccess) return+ if (projectStatusData?.status === PROJECT_STATUS.INACTIVE) {+ if (ref) {+ invalidateProjectDetailsQuery(ref)+ }+ invalidateProjectsQuery()+ }+ }, [+ isProjectStatusSuccess,+ projectStatusData,+ ref,+ invalidateProjectDetailsQuery,+ invalidateProjectsQuery,+ ])+useEffect(() => {setTimeout(() => setStartPolling(true), 4000)}, [])diff --git a/apps/studio/components/layouts/ProjectLayout/RestoringState.tsx b/apps/studio/components/layouts/ProjectLayout/RestoringState.tsxindex 3dd61bc05b4..d39bd4a382f 100644--- a/apps/studio/components/layouts/ProjectLayout/RestoringState.tsx+++ b/apps/studio/components/layouts/ProjectLayout/RestoringState.tsx@@ -1,5 +1,5 @@import { CheckCircle, Download, Loader } from 'lucide-react'-import { useState } from 'react'+import { useEffect, useState } from 'react'import { SupportCategories } from '@supabase/shared-types/out/constants'import { useParams } from 'common'@@ -12,6 +12,7 @@ import { useProjectStatusQuery } from 'data/projects/project-status-query'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { PROJECT_STATUS } from 'lib/constants'import { Button } from 'ui'+import status from 'http-status'const RestoringState = () => {const { ref } = useParams()@@ -26,23 +27,27 @@ const RestoringState = () => {const { invalidateProjectDetailsQuery } = useInvalidateProjectDetailsQuery()- useProjectStatusQuery(+ const { data: projectStatusData, isSuccess: isProjectStatusSuccess } = useProjectStatusQuery({ projectRef: ref },{enabled: project?.status !== PROJECT_STATUS.ACTIVE_HEALTHY,- refetchInterval: (res) => {- return res?.status === PROJECT_STATUS.ACTIVE_HEALTHY ? false : 4000- },- onSuccess: async (res) => {- if (res.status === PROJECT_STATUS.ACTIVE_HEALTHY) {- setIsCompleted(true)- } else {- if (ref) invalidateProjectDetailsQuery(ref)- }+ refetchInterval: (data) => {+ return data?.status === PROJECT_STATUS.ACTIVE_HEALTHY ? false : 4000},})+ useEffect(() => {+ if (!isProjectStatusSuccess) return+ if (projectStatusData.status === PROJECT_STATUS.ACTIVE_HEALTHY) {+ setIsCompleted(true)+ } else {+ if (ref) {+ invalidateProjectDetailsQuery(ref)+ }+ }+ }, [isProjectStatusSuccess, projectStatusData, ref, invalidateProjectDetailsQuery])+const { mutate: downloadBackup, isLoading: isDownloading } = useBackupDownloadMutation({onSuccess: (res) => {const { fileUrl } = resdiff --git a/apps/studio/data/config/jwt-secret-updating-status-query.ts b/apps/studio/data/config/jwt-secret-updating-status-query.tsindex 2aa7cbe86be..6e7e4831e55 100644--- a/apps/studio/data/config/jwt-secret-updating-status-query.ts+++ b/apps/studio/data/config/jwt-secret-updating-status-query.ts@@ -1,5 +1,7 @@import { JwtSecretUpdateStatus } from '@supabase/shared-types/out/events'import { useQuery, useQueryClient } from '@tanstack/react-query'+import { useEffect } from 'react'+import { get, handleError } from 'data/fetchers'import { UseCustomQueryOptions } from 'types'import { configKeys } from './keys'@@ -54,7 +56,7 @@ export const useJwtSecretUpdatingStatusQuery = <TData = JwtSecretUpdatingStatusD) => {const client = useQueryClient()- return useQuery<JwtSecretUpdatingStatusData, JwtSecretUpdatingStatusError, TData>({+ const query = useQuery({queryKey: configKeys.jwtSecretUpdatingStatus(projectRef),queryFn: ({ signal }) => getJwtSecretUpdatingStatus({ projectRef }, signal),enabled: enabled && typeof projectRef !== 'undefined',@@ -69,9 +71,14 @@ export const useJwtSecretUpdatingStatusQuery = <TData = JwtSecretUpdatingStatusDreturn interval},- onSuccess() {- client.invalidateQueries(configKeys.postgrest(projectRef))- },+...options,})++ useEffect(() => {+ if (!query.isSuccess) return+ client.invalidateQueries({ queryKey: configKeys.postgrest(projectRef) })+ }, [query.isSuccess, projectRef, client])++ return query}diff --git a/apps/studio/data/config/project-settings-v2-query.ts b/apps/studio/data/config/project-settings-v2-query.tsindex f43729766e0..4bced094db3 100644--- a/apps/studio/data/config/project-settings-v2-query.ts+++ b/apps/studio/data/config/project-settings-v2-query.ts@@ -54,7 +54,7 @@ export const useProjectSettingsV2Query = <TData = ProjectSettingsData>(queryFn: ({ signal }) => getProjectSettings({ projectRef }, signal),enabled: enabled && typeof projectRef !== 'undefined',refetchInterval(_data) {- const data = _data as ProjectSettings | undefined+ const data = _data as ProjectSettingsData | undefinedconst apiKeys = data?.service_api_keys ?? []const interval =canReadAPIKeys && data?.status !== 'INACTIVE' && apiKeys.length === 0 ? 2000 : 0diff --git a/apps/studio/data/config/project-upgrade-status-query.ts b/apps/studio/data/config/project-upgrade-status-query.tsindex a2eb8233f18..98b22b8e614 100644--- a/apps/studio/data/config/project-upgrade-status-query.ts+++ b/apps/studio/data/config/project-upgrade-status-query.ts@@ -1,9 +1,11 @@import { DatabaseUpgradeStatus } from '@supabase/shared-types/out/events'import { useQuery, useQueryClient } from '@tanstack/react-query'+import { useEffect } from 'react'+import { get, handleError } from 'data/fetchers'import { PROJECT_STATUS } from 'lib/constants'-import { configKeys } from './keys'import { UseCustomQueryOptions } from 'types'+import { configKeys } from './keys'export type ProjectUpgradingStatusVariables = {projectRef?: string@@ -43,7 +45,7 @@ export const useProjectUpgradingStatusQuery = <TData = ProjectUpgradingStatusDat) => {const client = useQueryClient()- return useQuery<ProjectUpgradingStatusData, ProjectUpgradingStatusError, TData>({+ const query = useQuery({queryKey: configKeys.upgradeStatus(projectRef),queryFn: ({ signal }) => getProjectUpgradingStatus({ projectRef, trackingId }, signal),enabled: enabled && typeof projectRef !== 'undefined',@@ -62,12 +64,17 @@ export const useProjectUpgradingStatusQuery = <TData = ProjectUpgradingStatusDatreturn interval},- onSuccess(data) {- const response = data as unknown as ProjectUpgradingStatusData- if (response.databaseUpgradeStatus?.status === DatabaseUpgradeStatus.Upgraded) {- client.invalidateQueries(configKeys.upgradeEligibility(projectRef))- }- },+...options,})++ useEffect(() => {+ if (!query.isSuccess) return+ const response = query.data as unknown as ProjectUpgradingStatusData+ if (response.databaseUpgradeStatus?.status === DatabaseUpgradeStatus.Upgraded) {+ client.invalidateQueries({ queryKey: configKeys.upgradeEligibility(projectRef) })+ }+ }, [query.isSuccess, query.data, projectRef, client])++ return query}diff --git a/apps/studio/data/projects/org-projects-infinite-query.ts b/apps/studio/data/projects/org-projects-infinite-query.tsindex ea367e8d110..855fbf61c11 100644--- a/apps/studio/data/projects/org-projects-infinite-query.ts+++ b/apps/studio/data/projects/org-projects-infinite-query.ts@@ -1,4 +1,5 @@import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query'+import { useCallback } from 'react'import { components } from 'api-types'import { get, handleError } from 'data/fetchers'@@ -93,8 +94,8 @@ export const getComputeSize = (project: OrgProject) => {export const useInvalidateProjectsInfiniteQuery = () => {const queryClient = useQueryClient()- const invalidateProjectsQuery = () => {+ const invalidateProjectsQuery = useCallback(() => {return queryClient.invalidateQueries({ queryKey: [INFINITE_PROJECTS_KEY_PREFIX] })- }+ }, [queryClient])return { invalidateProjectsQuery }}diff --git a/apps/studio/data/projects/project-detail-query.ts b/apps/studio/data/projects/project-detail-query.tsindex 8ba90592c07..432833bfa70 100644--- a/apps/studio/data/projects/project-detail-query.ts+++ b/apps/studio/data/projects/project-detail-query.ts@@ -1,4 +1,5 @@import { QueryClient, useQuery, useQueryClient } from '@tanstack/react-query'+import { useCallback } from 'react'import type { components } from 'data/api'import { get, handleError, isValidConnString } from 'data/fetchers'@@ -74,9 +75,12 @@ export function prefetchProjectDetail(client: QueryClient, { ref }: ProjectDetaiexport const useInvalidateProjectDetailsQuery = () => {const queryClient = useQueryClient()- const invalidateProjectDetailsQuery = (ref: string) => {- return queryClient.invalidateQueries({ queryKey: projectKeys.detail(ref) })- }+ const invalidateProjectDetailsQuery = useCallback(+ (ref: string) => {+ return queryClient.invalidateQueries({ queryKey: projectKeys.detail(ref) })+ },+ [queryClient]+ )return { invalidateProjectDetailsQuery }}diff --git a/apps/studio/hooks/misc/withAuth.tsx b/apps/studio/hooks/misc/withAuth.tsxindex e88fd610ae4..2e4588f21ed 100644--- a/apps/studio/hooks/misc/withAuth.tsx+++ b/apps/studio/hooks/misc/withAuth.tsx@@ -39,21 +39,30 @@ export function withAuth<T>(const timeoutIdRef = useRef<NodeJS.Timeout | null>(null)const [isSessionTimeoutModalOpen, setIsSessionTimeoutModalOpen] = useState(false)- const { isLoading: isAALLoading, data: aalData } = useAuthenticatorAssuranceLevelQuery({- onError(error) {+ const {+ isLoading: isAALLoading,+ data: aalData,+ isError: isErrorAAL,+ error: errorAAL,+ } = useAuthenticatorAssuranceLevelQuery()++ useEffect(() => {+ if (isErrorAAL) {toast.error(- `Failed to fetch authenticator assurance level: ${error.message}. Try refreshing your browser, or reach out to us via a support ticket if the issue persists`+ `Failed to fetch authenticator assurance level: ${errorAAL?.message}. Try refreshing your browser, or reach out to us via a support ticket if the issue persists`)- },- })+ }+ }, [isErrorAAL, errorAAL])- usePermissionsQuery({- onError(error: any) {+ const { isError: isErrorPermissions, error: errorPermissions } = usePermissionsQuery()++ useEffect(() => {+ if (isErrorPermissions) {toast.error(- `Failed to fetch permissions: ${error.message}. Try refreshing your browser, or reach out to us via a support ticket if the issue persists`+ `Failed to fetch permissions: ${errorPermissions?.message}. Try refreshing your browser, or reach out to us via a support ticket if the issue persists`)- },- })+ }+ }, [isErrorPermissions, errorPermissions])const isLoggedIn = Boolean(session)const isFinishedLoading = !isLoading && !isAALLoadingdiff --git a/apps/studio/lib/profile.tsx b/apps/studio/lib/profile.tsxindex 1970d60ad2d..0a971f27bf3 100644--- a/apps/studio/lib/profile.tsx+++ b/apps/studio/lib/profile.tsx@@ -1,6 +1,6 @@import * as Sentry from '@sentry/nextjs'import { useRouter } from 'next/router'-import { PropsWithChildren, createContext, useContext, useMemo } from 'react'+import { PropsWithChildren, createContext, useContext, useEffect, useMemo } from 'react'import { toast } from 'sonner'import { useIsLoggedIn, useUser } from 'common'@@ -77,22 +77,24 @@ export const ProfileProvider = ({ children }: PropsWithChildren<{}>) => {isSuccess,} = useProfileQuery({enabled: isLoggedIn,- onError(err) {- // if the user does not yet exist, create a profile for them- if (err.message === "User's profile not found") {- createProfile()- }-- // [Alaister] If the user has a bad auth token, auth-js won't know about it- // and will think the user is authenticated. Since fetching the profile happens- // on every page load, we can check for a 401 here and sign the user out if- // they have a bad token.- if (err.code === 401) {- signOut().then(() => router.push('/sign-in'))- }- },})+ useEffect(() => {+ if (!isError) return+ // if the user does not yet exist, create a profile for them+ if (error?.message === "User's profile not found") {+ createProfile()+ }++ // [Alaister] If the user has a bad auth token, auth-js won't know about it+ // and will think the user is authenticated. Since fetching the profile happens+ // on every page load, we can check for a 401 here and sign the user out if+ // they have a bad token.+ if (error?.code === 401) {+ signOut().then(() => router.push('/sign-in'))+ }+ }, [error, signOut, router, createProfile, isError])+const { isInitialLoading: isLoadingPermissions } = usePermissionsQuery({ enabled: isLoggedIn })const value = useMemo(() => {diff --git a/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx b/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsxindex d96812b48ad..49beed946d2 100644--- a/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx+++ b/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx@@ -1,5 +1,5 @@import { useParams } from 'common'-import { ChangeEvent, useState } from 'react'+import { ChangeEvent, useEffect, useState } from 'react'import { toast } from 'sonner'import { Alert, Button, Checkbox, Input, Listbox } from 'ui'@@ -152,7 +152,7 @@ const CreateProject = () => {}// Wait for the new project to be created before creating the connection- useProjectSettingsV2Query(+ const { data, isSuccess } = useProjectSettingsV2Query({ projectRef: newProjectRef },{enabled: newProjectRef !== undefined,@@ -160,46 +160,50 @@ const CreateProject = () => {refetchInterval: (data) => {return ((data?.service_api_keys ?? []).length ?? 0) > 0 ? false : 1000},- async onSuccess(data) {- const isReady = (data?.service_api_keys ?? []).length > 0+ }+ )+ useEffect(() => {+ if (!isSuccess) return+ const onSuccessFunc = async () => {+ const isReady = (data.service_api_keys ?? []).length > 0- if (!isReady || !organizationIntegration || !foreignProjectId || !newProjectRef) {- return- }+ if (!isReady || !organizationIntegration || !foreignProjectId || !newProjectRef) {+ return+ }- const projectDetails = vercelProjects?.find((x: any) => x.id === foreignProjectId)+ const projectDetails = vercelProjects?.find((x: any) => x.id === foreignProjectId)- try {- const { id: connectionId } = await createConnections({- organizationIntegrationId: organizationIntegration?.id,- connection: {- foreign_project_id: foreignProjectId,- supabase_project_ref: newProjectRef,- integration_id: '0',- metadata: {- ...projectDetails,- supabaseConfig: {- projectEnvVars: {- write: true,- },+ try {+ await createConnections({+ organizationIntegrationId: organizationIntegration?.id,+ connection: {+ foreign_project_id: foreignProjectId,+ supabase_project_ref: newProjectRef,+ integration_id: '0',+ metadata: {+ ...projectDetails,+ supabaseConfig: {+ projectEnvVars: {+ write: true,},},},- orgSlug: selectedOrganization?.slug,- })- } catch (error) {- console.error('An error occurred during createConnections:', error)- return- }+ },+ orgSlug: selectedOrganization?.slug,+ })+ } catch (error) {+ console.error('An error occurred during createConnections:', error)+ return+ }- snapshot.setLoading(false)+ snapshot.setLoading(false)- if (next && isVercelUrl(next)) {- window.location.href = next- }- },+ if (next && isVercelUrl(next)) {+ window.location.href = next+ }}- )+ onSuccessFunc()+ }, [data, isSuccess])return (<div>diff --git a/apps/studio/pages/project/[ref]/database/column-privileges.tsx b/apps/studio/pages/project/[ref]/database/column-privileges.tsxindex 6b39bbab9f2..a2921a2cd6c 100644--- a/apps/studio/pages/project/[ref]/database/column-privileges.tsx+++ b/apps/studio/pages/project/[ref]/database/column-privileges.tsx@@ -1,7 +1,7 @@import { LOCAL_STORAGE_KEYS, useParams } from 'common'import { AlertCircle, XIcon } from 'lucide-react'import Link from 'next/link'-import { useCallback, useMemo, useState } from 'react'+import { useCallback, useEffect, useMemo, useState } from 'react'import { toast } from 'sonner'import {@@ -47,23 +47,24 @@ const PrivilegesPage: NextPageWithLayout = () => {const [selectedTable, setSelectedTable] = useState<string | undefined>(paramTable)const [selectedRole, setSelectedRole] = useState<string>('authenticated')- const { data: tableList, isLoading: isLoadingTables } = useTablesQuery(- {- projectRef: project?.ref,- connectionString: project?.connectionString,- },- {- onSuccess(data) {- const tables = data- .filter((table) => table.schema === selectedSchema)- .map((table) => table.name)-- if (tables[0] && selectedTable === undefined) {- setSelectedTable(tables[0])- }- },+ const {+ data: tableList,+ isLoading: isLoadingTables,+ isSuccess: isSuccessTables,+ } = useTablesQuery({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ })++ useEffect(() => {+ if (!isSuccessTables) return+ const tables = tableList+ .filter((table) => table.schema === selectedSchema)+ .map((table) => table.name)+ if (tables[0] && selectedTable === undefined) {+ setSelectedTable(tables[0])}- )+ }, [isSuccessTables, tableList, selectedSchema, selectedTable])const { data: allRoles, isLoading: isLoadingRoles } = useDatabaseRolesQuery({projectRef: project?.ref,diff --git a/apps/studio/pages/project/[ref]/observability/index.tsx b/apps/studio/pages/project/[ref]/observability/index.tsxindex 522f1772c44..67cf5b12f8c 100644--- a/apps/studio/pages/project/[ref]/observability/index.tsx+++ b/apps/studio/pages/project/[ref]/observability/index.tsx@@ -1,6 +1,6 @@import { PermissionAction } from '@supabase/shared-types/out/constants'import { useRouter } from 'next/router'-import { useState } from 'react'+import { useEffect, useState } from 'react'import { useParams } from 'common'import { CreateReportModal } from 'components/interfaces/Reports/CreateReportModal'@@ -20,21 +20,20 @@ export const UserReportPage: NextPageWithLayout = () => {const { profile } = useProfile()const [showCreateReportModal, setShowCreateReportModal] = useState(false)- const { isLoading } = useContentQuery(- {- projectRef: ref,- type: 'report',- },- {- onSuccess: (data) => {- const reports = data.content- .filter((x) => x.type === 'report')- .sort((a, b) => a.name.localeCompare(b.name))- if (reports.length >= 1) router.push(`/project/${ref}/observability/${reports[0].id}`)- if (reports.length === 0) router.push(`/project/${ref}/observability/api-overview`)- },- }- )+ const { isLoading, isSuccess, data } = useContentQuery({+ projectRef: ref,+ type: 'report',+ })++ useEffect(() => {+ if (!isSuccess) return++ const reports = data.content+ .filter((x) => x.type === 'report')+ .sort((a, b) => a.name.localeCompare(b.name))+ if (reports.length >= 1) router.push(`/project/${ref}/observability/${reports[0].id}`)+ if (reports.length === 0) router.push(`/project/${ref}/observability/api-overview`)+ }, [isSuccess, data, router, ref])const { can: canCreateReport } = useAsyncCheckPermissions(PermissionAction.CREATE,