Studio Queries & Mutations (React Query)

VerifiedSafe

React Query conventions for data fetching in Supabase Studio: query keys, queryOptions, mutation hooks, and imperative fetching.

Sby Skills Guide Bot
DevelopmentIntermediate
8/29/2026
Claude CodeCursorCodex
#react-query#data-fetching#query-keys#mutation-hooks#supabase-studio

Recommended for

Automated summary

Describes the React Query conventions (query keys, queryOptions, mutation hooks, imperative fetching) to follow inside Supabase Studio's apps/studio/data/ directory.

Strengths

  • Ships complete, typed templates for queryOptions and mutation hooks
  • Enforces a per-domain keys.ts with `as const` array keys instead of inline keys
  • Explains imperative fetching with queryClient.fetchQuery reusing the same queryOptions
  • States the invalidation rules (list + detail) and the default error toast

Limitations

  • Tightly coupled to the Supabase Studio repo: file paths, internal helpers (handleError, IS_PLATFORM, @/data/fetchers) and the ResponseError type
  • Covers only the React Query data layer, not global state, forms or UI
  • The mutation hook snippet is truncated in the document, so you must consult the referenced example files
When to use it

Use it whenever you write or review a query hook, query key or mutation under apps/studio/data/.

When not to use it

Skip it on projects that do not use Supabase Studio, TanStack Query or these internal helpers, since the templates would not apply.

Security analysis

Safe
Quality score88/100

This skill is purely documentation of React Query conventions for a Supabase Studio codebase. It contains only illustrative TypeScript patterns (query keys, queryOptions, mutation hooks, imperative fetching) with no executable commands, no network/curl calls, no credential handling, and no destructive or obfuscated operations. No allowed-tools are declared and nothing instructs an agent to run shell commands or modify system state.

No concerns found

How this analysis is made

Examples

New endpoint query hook
Add the first data fetch for the new /v1/projects/{ref}/branches endpoint in apps/studio/data/ — create keys.ts and the query options file following our React Query conventions.
Review a mutation hook
Review this mutation hook in apps/studio/data/edge-functions/ and check that it invalidates the right keys and handles errors per our conventions.
Fetching inside a callback
I need to load a project's details inside an onClick handler, not with useQuery — how should I do that with our queryOptions pattern?

name: studio-queries description: React Query conventions for data fetching in Supabase Studio. Use when writing or reviewing query hooks, mutation hooks, or query keys in apps/studio/data/ — including adding the first fetch or mutation for a new API endpoint or resource. Covers queryOptions pattern, keys.ts structure, mutation hook template, and imperative fetching.

Studio Queries & Mutations (React Query)

Follow the patterns in apps/studio/data/. Reference examples:

  • Query options: apps/studio/data/table-editor/table-editor-query.ts
  • Mutation hook: apps/studio/data/edge-functions/edge-functions-update-mutation.ts
  • Keys: apps/studio/data/edge-functions/keys.ts

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,
}

Query Options (preferred pattern)

Use queryOptions from @tanstack/react-query. This gives type safety and works with both useQuery() and queryClient.fetchQuery().

Rules:

  • Export XVariables, XData, and XError types (prefixed with the domain name)
  • Implement a private getX(variables, signal?) function:
    • Throws if required variables are missing
    • Passes signal for cancellation
    • Calls handleError(error) on failure (which throws); returns data on success
    • Not exported — use queryClient.fetchQuery(xQueryOptions(...)) for imperative fetching
  • Export xQueryOptions() using queryOptions
  • Gate with enabled so the query doesn't run until required variables exist
  • Platform-only queries: include IS_PLATFORM from lib/constants in enabled
  • Don't add extra params to xQueryOptions — callers override by destructuring: { ...xQueryOptions(vars), enabled: true }
import { queryOptions } from '@tanstack/react-query'

import { xKeys } from './keys'
import { get, handleError } from '@/data/fetchers'
import { IS_PLATFORM } from '@/lib/constants'
import { ResponseError } from '@/types'

export type XVariables = { projectRef?: string }
export type XError = ResponseError

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({
    queryKey: xKeys.list(projectRef),
    queryFn: ({ signal }) => getX({ projectRef }, signal),
    enabled: IS_PLATFORM && typeof projectRef !== 'undefined',
  })

Using Query Options in Components

import { useQuery } from '@tanstack/react-query'

import { xQueryOptions } from '@/data/x/x-query'

const { data, isPending, isError } = useQuery(xQueryOptions({ projectRef: project?.ref }))

Imperative Fetching (outside React or in callbacks)

const queryClient = useQueryClient()
const { data: project } = useSelectedProjectQuery()

const handleClick = useCallback(
  async (id: number) => {
    const data = await queryClient.fetchQuery(xQueryOptions({ id, projectRef: project?.ref }))
    // use data...
  },
  [project?.ref, queryClient]
)

Mutation Hook

  • Export a Variables type with projectRef, identifiers, and payload
  • Implement a private updateX(vars) function with required variable validation and handleError
  • Wrap in useXMutation():
    • Accepts UseMutationOptions (omit mutationFn)
    • Invalidates list() + detail() keys in onSuccess with await Promise.all([...])
    • Defaults to toast.error(...) when onError isn't provided
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'

import { xKeys } from './keys'

type XUpdateVariables = { projectRef: string; slug: string; payload: XPayload }

export const useXUpdateMutation = ({
  onSuccess,
  onError,
  ...options
}: UseMutationOptions<XData, XError, XUpdateVariables> = {}) => {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: updateX,
    async onSuccess(data, variables, context) {
      await Promise.all([
        queryClient.invalidateQueries({
          queryKey: xKeys.detail(variables.projectRef, variables.slug),
        }),
        queryClient.invalidateQueries({ queryKey: xKeys.list(variables.projectRef) }),
      ])
      await onSuccess?.(data, variables, context)
    },
    async onError(error, variables, context) {
      if (onError === undefined) toast.error(`Failed to update: ${error.message}`)
      else onError(error, variables, context)
    },
    ...options,
  })
}

Component Usage

  • Use React Query v5 flags: isPending for initial load, isFetching for background refetches
  • Render states explicitly in order: pending → error → success

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/studio-queries-mutations-react-query-mte1lfoz/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/studio-queries-mutations-react-query-mte1lfoz' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/studio-queries-mutations-react-query-mte1lfoz/download' --output '.skill-downloads/studio-queries-mutations-react-query-mte1lfoz/SKILL.md.part' && mv '.skill-downloads/studio-queries-mutations-react-query-mte1lfoz/SKILL.md.part' '.skill-downloads/studio-queries-mutations-react-query-mte1lfoz/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/studio-queries-mutations-react-query-mte1lfoz/SKILL.md' && test -s '.skill-downloads/studio-queries-mutations-react-query-mte1lfoz/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/studio-queries' && cp -R '.skill-downloads/studio-queries-mutations-react-query-mte1lfoz' '.claude/skills/studio-queries'

Cursor
test -f '.skill-downloads/studio-queries-mutations-react-query-mte1lfoz/SKILL.md' && test -s '.skill-downloads/studio-queries-mutations-react-query-mte1lfoz/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/studio-queries' && cp -R '.skill-downloads/studio-queries-mutations-react-query-mte1lfoz' '.cursor/skills/studio-queries'

Codex
test -f '.skill-downloads/studio-queries-mutations-react-query-mte1lfoz/SKILL.md' && test -s '.skill-downloads/studio-queries-mutations-react-query-mte1lfoz/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/studio-queries' && cp -R '.skill-downloads/studio-queries-mutations-react-query-mte1lfoz' '.agents/skills/studio-queries'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/studio-queries-mutations-react-query-mte1lfoz'

openskills read 'studio-queries-mutations-react-query-mte1lfoz'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/studio-queries-mutations-react-query-mte1lfoz/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills