studio-queries
par supabase
Conventions React Query pour la récupération de données dans Supabase Studio. Utiliser lorsque
npx skills add https://github.com/supabase/supabase --skill studio-queriesStudio Queries & Mutations (React Query)
Follow the patterns in apps/studio/data/. Reference examples:
- Query options:
apps/studio/data/storage/bucket-lifecycle-query.ts(plain) andapps/studio/data/jwt-signing-keys/jwt-signing-keys-query.ts(grantedQueryOptions) - Mutation hook:
apps/studio/data/storage/versioning/archived-object-restore-mutation.ts - Keys:
apps/studio/data/edge-functions/keys.ts
Folder Boundaries
- Keep
apps/studio/data/strictly for React Query queries, mutations, and query keys — never put UI formatting or URL helpers indata/(colocate those with the feature undercomponents/interfaces/). - Pass scoping identifiers (
projectRef,clusterId, etc.) explicitly invariables— never read ambient React Context insidedata/**hooks. - Keep
create-*-mutation.tsandupdate-*-mutation.tsseparated; put shared payload builders and types in siblingtypes.ts/utils.tsfiles inside the domain folder. - Derive response types from generated
packages/api-types(see api-types) — fix contract drift at the source rather than hiding it withas unknown as CustomTypeor defensiveArray.isArray(data) ? data : []shims.
Query Keys
Define a keys.ts per domain. Export *Keys helpers using array keys with as const. Never inline query keys in components.
export const edgeFunctionsKeys = {
list: (projectRef: string | undefined) => ['projects', projectRef, 'edge-functions'] as const,
detail: (projectRef: string | undefined, slug: string | undefined) =>
['projects', projectRef, 'edge-function', slug, 'detail'] as const,
metrics: (projectRef: string | undefined, params?: { interval?: string; limit?: number }) =>
['projects', projectRef, 'edge-functions', 'metrics', ...(params ? [params] : [])] as const,
}
Key hygiene rules:
- Never flatten multiple optional positional params with
.filter():[..., limit, offset].filter((v) => v !== undefined)collides when(10, undefined)vs(undefined, 10). Group optional filter/pagination params into one object and spread trailing optional params (...(params ? [params] : [])) sokeys.metrics(ref)doubles as the prefix key for invalidation. - Never fork/suffix cache keys for the same underlying endpoint (e.g.
[...queryKey, 'permission-safe']) — reuse the canonicalqueryOptionsand layerselector fallbacks on top. - Pass key-factory keys to
invalidateQueries/removeQueries(never manual array-index predicates), and check TanStack Query prefix matching before issuing redundant child invalidations.
Query Options (preferred pattern)
Use queryOptions from @tanstack/react-query so one definition works for both useQuery() and queryClient.fetchQuery().
- Export domain-prefixed
XVariables,XData, andXErrortypes. - Implement a private
getX(variables, signal?)function that validates required variables, forwardssignal, callshandleError(error)on failure, and returnsdata. Do not export it — usequeryClient.fetchQuery(xQueryOptions(...))for imperative fetching. - Export
xQueryOptions()gated withenabledon required variables (plusIS_PLATFORMfromlib/constantsfor platform-only queries). - Parent
isPendingtrap: when gating on a negated value derived from another async query (e.g.enabled: !isHighAvailability), also gate on!isParentPending(enabled: !isPending && !isHighAvailability) so it does not fire while the parent query is unsettled. - Default optional opt-in enable flags to
false(safe-by-default), nevertrue. - Match query params (such as
limit) across sibling consumers so they share one cache entry. - Custom polling & retries:
apps/studio/data/query-client.tsalready skips 4xx (except 429) and retries 429/5xx globally. When writing customrefetchIntervalorretryoverrides, use a conservative interval (e.g.5_000ms, never1_000ms), back off on allerror.code >= 400, and retry transient error classes (error.code === 429 || error.code >= 500) rather than individual status codes. - Caller overrides &
enabled: spread non-enabledoptions ({ ...xQueryOptions(vars), select, refetchInterval }) freely. Never overrideenableddirectly (e.g.{ ...xQueryOptions(vars), enabled: isOpen }) — that clobbers the factory'sIS_PLATFORM/ required-variable gate. Instead, preserve the factory gate (const opts = xQueryOptions(vars); useQuery({ ...opts, enabled: opts.enabled !== false && isOpen })) or accept an optional 2nd{ enabled = true }arg in the factory and AND it with the factory's gates (except grant-gated queries below, which always take caller options as the 2nd arg).
import { queryOptions } from '@tanstack/react-query'
import { xKeys } from './keys'
import { get, handleError } from '@/data/fetchers'
import { IS_PLATFORM } from '@/lib/constants'
import type { StudioError } from '@/lib/errors/studio-errors'
export type XVariables = { projectRef?: string }
export type XError = StudioError
async function getX({ projectRef }: XVariables, signal?: AbortSignal) {
if (!projectRef) throw new Error('projectRef is required')
const { data, error } = await get('/v1/projects/{ref}/x', {
params: { path: { ref: projectRef } },
signal,
})
if (error) handleError(error)
return data
}
export type XData = Awaited<ReturnType<typeof getX>>
export const xQueryOptions = ({ projectRef }: XVariables) =>
queryOptions<XData, XError>({
queryKey: xKeys.list(projectRef),
queryFn: ({ signal }) => getX({ projectRef }, signal),
enabled: IS_PLATFORM && typeof projectRef !== 'undefined',
})
Grant-gated Queries
Query options requiring a grant (lib/grants.ts) use grantedQueryOptions from @/data/granted-query-options and accept caller options as the second argument. Never spread or Object.assign them (fga/no-spread-granted-query-options enforces this via the branded __grantedQueryOptions return type).
- Pass
queryFn: undefined(neverskipToken, which breaks invalidation when a grant-less observer shares the cache entry) when a grant or required variable is missing;grantedQueryOptionsforcesenabled: falseand supplies a delegating fallbackqueryFn(avoiding TanStack's devNo queryFnerror). - The factory owns
queryKey,queryFn, and the grantenabledgate so callers cannot override the grant check.
export const xQueryOptions = <TData = XData>(
{ projectRef, grant }: XVariables,
options?: GrantedQueryCallerOptions<XData, XError, TData, ReturnType<typeof xKeys.list>>
) =>
grantedQueryOptions(
{
queryKey: xKeys.list(projectRef),
queryFn:
projectRef && grant ? ({ signal }) => getX({ projectRef, grant }, signal) : undefined,
},
options
)
// Caller
useQuery(xQueryOptions({ projectRef, grant: xGrant.grant }, { select, enabled: open }))
Component & Imperative Usage
// Component
const { data, isPending, isError } = useQuery(xQueryOptions({ projectRef: project?.ref }))
// Imperative (callbacks / outside React) — fetchQuery ignores `enabled`, so mirror factory gates first
const queryClient = useQueryClient()
if (IS_PLATFORM && project?.ref) {
const data = await queryClient.fetchQuery(xQueryOptions({ projectRef: project.ref }))
}
- Use React Query v5 flags (
isPendingfor initial load,isFetchingfor background refetches) and render states in order: pending → error → success. - Call query hooks directly in consuming child/modal components instead of fetching in a parent solely to prop-drill
data/isPending/isError; useselectfor single-consumer derived values instead of one-off wrapper hooks. - Gate infinite-scroll
fetchNextPage()behind!isFetching(or!isFetchingNextPage) to prevent duplicate page requests. - Never
await mutate(...)(mutatereturnsvoid). Prefermutate+ callbacks overmutateAsyncunless a Promise is needed (e.g. an async dialog loading state or sequential flow), and always wrapmutateAsyncintry/catch(never emptycatch { return }). - Read mutation
errordirectly fromuseMutation()instead of mirroring it inuseState, and pass cross-callback mutation state via React Querycontext(onMutate→onSuccess/onSettled) instead of auseRef.
Mutation Hook
- Export a
Variablestype (projectRef, identifiers,payload), implement a privateupdateX(vars)function with variable validation andhandleError, and wrap inuseXMutation()acceptingOmit<UseMutationOptions<...>, 'mutationFn'>(forwarding all 4 TanStack v5 callback args; existing hooks usingUseCustomMutationOptionsfrom@/typesuse a 3-arg callback contract). - Don't destructure
onSuccessunless adding customonSuccesslogic — otherwise calleronSuccesscallbacks are silently swallowed (let...optionsforward it). - In
onSuccess,await Promise.all([...])to invalidate every view staled by the mutation via key factories, without wiping freshly prefetched keys or unrelated user/resource scopes. - Single-layer error toasts: default to
toast.error(...)only whenonError === undefined; if callers handle errors inline or imperatively viamutateAsync+catch, pass a customonError(or omit the default toast when all callers handle errors themselves) to avoid duplicate toasts.
import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query'
import { toast } from 'sonner'
import { xKeys } from './keys'
type XUpdateVariables = { projectRef: string; slug: string; payload: XPayload }
export const useXUpdateMutation = ({
onSuccess,
onError,
...options
}: Omit<UseMutationOptions<XData, XError, XUpdateVariables>, 'mutationFn'> = {}) => {
const queryClient = useQueryClient()
return useMutation<XData, XError, XUpdateVariables>({
mutationFn: updateX,
async onSuccess(data, variables, context, mutationContext) {
await Promise.all([
queryClient.invalidateQueries({
queryKey: xKeys.detail(variables.projectRef, variables.slug),
}),
queryClient.invalidateQueries({ queryKey: xKeys.list(variables.projectRef) }),
])
await onSuccess?.(data, variables, context, mutationContext)
},
async onError(error, variables, context, mutationContext) {
if (onError === undefined) toast.error(`Failed to update: ${error.message}`)
else await onError(error, variables, context, mutationContext)
},
...options,
})
}