Manages reactive data fetching, caching, and mutation state using TanStack Query.

Install

mkdir -p .claude/skills/query-layer && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/4567" && unzip -o skill.zip -d .claude/skills/query-layer && rm skill.zip

Installs to .claude/skills/query-layer

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Query/RPC layer with TanStack Query, defineKeys, service composition, runtime DI. Use for createQuery, createMutation, queries/mutations, reactive data management.
163 chars✓ has a “when” trigger
Advanced

Key capabilities

  • →Define canonical query keys
  • →Manage reactive data caching
  • →Implement optimistic cache updates
  • →Orchestrate service-layer dependency injection

How it works

It uses factories to wrap service methods in Query/Mutation objects, managing the lifecycle of the request inside the TanStack cache engine.

Inputs & outputs

You give it
Service function call and metadata definitions
You get back
Reactive hook binding to UI components

When to use query-layer

  • →Implementing reactive data fetching
  • →Managing query cache and invalidation
  • →Handling optimistic UI updates
  • →Structuring service layer queries

About this skill

Query layer

The query layer turns Result-returning services into TanStack Query options for UI to observe. Services stay TanStack-free and return Results; the layer adds cache identity, observation, and refresh after writes. Everything in it is plain TanStack options, so TanStack's own mechanisms do the composing.

Related skills: svelte for component-level hook use, error-handling for presenting a failure.

What a service is

A service is a group of related functions for one job, usually methods on a plain object or a factory result. It is independent of the UI framework: it can make requests, write files, and keep state, but it does not import Svelte or React, read component state, or decide what the interface shows. Toasts, reporting, and TanStack observers stay outside it.

Dependencies are explicit. Capture a stable resource at construction when several operations share it; pass per-call inputs to the operation. Expected failures return Result<T, E>; infallible work stays an ordinary value. Keep lower-layer tagged errors as they are and define a local one only for a failure the service owns.

Ground before relying on memory

Ground the Wellcrafted side in wellcrafted/query as installed (0.47, source and README in wellcrafted-dev/wellcrafted). When TanStack behavior affects correctness, such as invalidation, mutation callback order, or adapter types, ask DeepWiki a narrow question about TanStack/query, then confirm the deciding detail in the installed @tanstack/query-core source. Skip this for the patterns below.

Compose a service into two maps

Wrap the reads a UI observes in resultQueries and the writes in resultMutations. The first argument is the namespace, which starts every key; the second names the service functions:

const billingQueries = resultQueries(['billing'], {
	overview: billingApi.overview,
	usage: billingApi.usage,
	plans: billingApi.plans,
});

const billingMutations = resultMutations(['billing'], {
	checkoutPlan: billingApi.checkoutPlan,
	checkoutTopUp: billingApi.checkoutTopUp,
});

Each key is the namespace, then the method name. A query key also ends with the call's arguments, kept together in one list:

billingQueries.usage.key                   // ['billing', 'usage']
billingQueries.usage(params).queryKey      // ['billing', 'usage', [params]]
billingMutations.checkoutTopUp.mutationKey // ['billing', 'checkoutTopUp']

The list keeps arguments apart from names, so an argument never reads as a method or namespace. Use .key for defaults that cover every call of a method; .queryKey is one cached answer, typed for getQueryData and setQueryData. Every entry sends Err to TanStack's error path, so success callbacks, such as a form reset, run only when the write succeeds.

  • A query takes its method's own arguments. A mutation's method takes no arguments or one input object, and only that input reaches it.
  • Pass functions only: bound methods or closures, with annotated parameters on a new wrapper. A wrapper that fixes a transport option is fine: session: () => management.getSession({ query: { disableCookieCache: true } }).
  • Query arguments become the key. Keep them stable and serializable, and normalize before calling the factory when f() and f(undefined) should share an entry.

Hooks take entries directly, with no .options hop:

const overview = createQuery(() => billingQueries.overview());
const topUp = createMutation(() => billingMutations.checkoutTopUp);
topUp.mutate({ successUrl: window.location.href }, { onSuccess, onError });

Group a feature's maps by resource

A namespace can have more than one part. When a feature already has distinct resource groups, prefer a plain object that mirrors them. Each property names its resource, so methods can use short verbs like set and delete.

const folderMutations = {
	notes: resultMutations(['folder', 'notes'], {
		set: notes.set,
		replace: notes.replace,
		delete: notes.delete,
	}),
	settings: resultMutations(['folder', 'settings'], { set: folder.settings.set }),
	audio: resultMutations(['folder', 'audio'], {
		delete: folder.deleteAudio,
		deleteBefore: folder.deleteAudioBefore,
	}),
};

folderMutations.notes.delete is keyed ['folder', 'notes', 'delete']. One flat map is still fine when its methods read clearly together.

Make writes take turns

TanStack runs writes in parallel. To run a group one at a time, in the order they were made, give the group's key prefix a shared scope:

queryClient.setMutationDefaults(['folder'], { scope: { id: 'folder' } });

Every mutation keyed under ['folder'] now waits for the one before it, and the services stay unchanged. The prefix decides who waits, so key a write outside it when it must not hold up the others: a slow transcription keyed ['runs'] does not delay every save to the folder.

Capture the submitted operation

Read data, pending, error, and submitted variables from their query or mutation. First try removing local state that mirrors these values. Keep an independent draft when the interface needs information the operation does not own.

Capture submitted values, record identity, and any reviewed version in the interaction handler before calling mutate(input), mutateAsync(input), or starting an awaited workflow. Let mutationFn receive that input. If someone presses Send in thread A and opens thread B while the draft saves, the reply still belongs to thread A. Capture the thread ID with the text at Send. Read event or control values synchronously. Passing a live form or a callback that reads the editor later changes which values the operation uses. Closures over stable services or identity fixed for the component's lifetime remain useful.

Passing an object to mutate passes a reference. Check who can still change it, including the receiving API. Capture the submitted fields or detach mutable parts when needed. Replacing the draft on each edit can already preserve the submission if its nested values also stay unchanged.

Svelte's input ownership applies this rule to native controls, reactive drafts, and completion-time clearing.

One rule refreshes reads after every write

Give each QueryClient one MutationCache rule, where the client is created:

const queryClient = new QueryClient({
	mutationCache: new MutationCache({
		onSettled: (_data, _error, _variables, _rollback, _mutation, { client }) =>
			client.invalidateQueries(),
	}),
});

After any write, finished or failed, every query goes stale. Only observed queries refetch now; the rest refetch when next used. The rule reads nothing from the write's key, so it cannot miss a read elsewhere, and it runs alongside an entry's own callbacks, so a spread cannot drop it. Returning the promise keeps the write pending until what is on screen is fresh.

So do not call invalidateQueries after a write in a component or a mutation callback. An operation that changes nothing is a read, whatever its HTTP method: a plan-change preview sent as a POST is a query keyed by plan, enabled while its dialog is open. Modelling it as a mutation would need a reset before each use, a guard that its answer is for the open plan, and an exception to the rule. If one write's refetches ever cost too much, Wellcrafted documents a meta.invalidates opt-in; a precise list goes stale silently when a new read starts depending on the write, so adopt it only for that measured cost. Do not work out which reads a write affects by slicing its mutation key.

The rule covers one client. Code that creates a client per account or connection gets one rule per client, and none touches another client's cache.

Compose by spread

Put behavior where it applies:

Applies toWhereExample
One useSpread into the hook's optionscreateQuery(() => ({ ...billingQueries.plans(), select: (p) => p.cards }))
A method or namespaceClient defaults by key prefixqueryClient.setQueryDefaults(billingQueries.overview.key, { refetchOnWindowFocus: 'always' })
A variant several components shareSpread into mutationOptions and export itbelow

TanStack infers what a spread adds, including select. Matching defaults merge in registration order, so register a broad prefix before a narrow one. Spreading options and defining the same callback replaces it; preserve the existing work, order, and awaited promises when extending one.

A shared variant reaches the cache through the query factories' keys, so define the reads first; writes refer to reads, never the reverse:

export const updateUser = mutationOptions({
	...userMutations.update,
	onSuccess: (saved, _input, _rollback, { client }) =>
		client.setQueryData(userQueries.get(saved.id).queryKey, saved),
});

For an optimistic change shown in one place, render mutation.variables while the write is pending and leave the cache alone: there is nothing to roll back. Update the cache in onMutate, cancel the read first, and restore the snapshot in onError only when several places must show the change at once.

Put essential per-execution work in mutation options or that call's promise. Per-call mutate callbacks belong to the latest observed interaction. Read mutation lifecycle when changing callback ownership, awaited completion, overlapping submissions, or sensitive inputs.

Run options imperatively

Outside a hook, or when a handler needs the outcome as a Result, run the same options through the client:

const { error } = await runMutation(queryClient, accountMutations.deletePasskey, {
	id: passkey.id,
});
if (error) return reportError(error, 'Could not remove this passkey.');

`runMutati


Content truncated.

When not to use it

  • →Purely static data fetching
  • →Small frontends where state management overhead is overkill

Prerequisites

TanStack QuerySvelte or relevant framework adapter

Limitations

  • →Requires strict adherence to key definition patterns
  • →Complex cache invalidation logic can be error-prone

How it compares

Instead of manual state flags for loading/error, it automatically syncs component state with server cache.

Compared to similar skills

query-layer side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
query-layer (this skill)15moNo flagsAdvanced
frontend-api-integration-patterns06moReviewIntermediate
zustand1135moNo flagsIntermediate
accessibility-compliance456moNo flagsIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

You might also like

frontend-api-integration-patterns

TJSNDHU

Production-ready patterns for integrating frontend applications with backend APIs, including race condition handling, request cancellation, retry strategies, error normalization, and UI state management.

00

zustand

lobehub

Zustand state management guide. Use when working with store code (src/store/**), implementing actions, managing state, or creating slices. Triggers on Zustand store development, state management questions, or action implementation.

113434

accessibility-compliance

wshobson

Implement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.

45132

react-modernization

wshobson

Upgrade React applications to latest versions, migrate from class components to hooks, and adopt concurrent features. Use when modernizing React codebases, migrating to React Hooks, or upgrading to latest React versions.

21134

react

lobehub

React component development guide. Use when working with React components (.tsx files), creating UI, using @lobehub/ui components, implementing routing, or building frontend features. Triggers on React component creation, modification, layout implementation, or navigation tasks.

3480

frontend-testing

langgenius

Generate Vitest + React Testing Library tests for Dify frontend components, hooks, and utilities. Triggers on testing, spec files, coverage, Vitest, RTL, unit tests, integration tests, or write/review test requests.

1152

Search skills

Search the agent skills registry