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 Patterns

Reference Repositories

Upstream Grounding

When TanStack Query behavior, Svelte adapter types, cache invalidation semantics, optimistic updates, or mutation lifecycle callbacks affect correctness, ask DeepWiki a narrow question against TanStack/query before relying on memory. Use it to orient, then verify decisive details against local installed types, source, or official docs before changing code.

Skip DeepWiki for stable basics and repo-local patterns already documented below.

The query layer is the reactive bridge between UI components and the service layer. It wraps service functions or observable operations with caching, mutation lifecycle state, invalidation, and direct imperative access using TanStack Query and Wellcrafted factories.

Related Skills: See services-layer for the service layer these queries consume. See svelte for Svelte-specific TanStack Query patterns. See error-handling for toast/report patterns after Results reach the UI boundary.

Core Architecture

┌─────────────┐     ┌─────────────┐     ┌──────────────┐
│     UI      │ --> │    Query    │ --> │   Services   │
│ Components  │     │    Layer    │     │  (UI-free)   │
└─────────────┘     └─────────────┘     └──────────────┘
      ↑                    │
      └────────────────────┘
         Reactive Updates

Query Layer Responsibilities:

  • Call services with injected settings/configuration
  • Preserve typed service and operation errors unless the adapter introduces a new local failure
  • Manage TanStack Query cache for optimistic updates
  • Provide hook-ready .options for shared definitions and explicit imperative APIs where they exist
  • Own shared cache identity through exported *Keys maps

Wellcrafted Query API Shape

ScopeQueryMutation
Hook-local Result adapterresultQueryOptions(input)resultMutationOptions(input)
Reusable definitiondefineQuery(input)defineMutation(input)

Use resultQueryOptions and resultMutationOptions at one hook call site when a Result-returning function needs to enter TanStack's data/error channels and no imperative API or shared query identity is needed.

Use defineQuery and defineMutation in shared $lib/queries modules.

Queries expose .options, .fetch(), and .ensure(). They are not callable.

Mutations expose .options and are callable. They do not expose .execute().

Canonical Whispering Query Module Shape

For Whispering-style $lib/queries modules, keep source-of-truth declarations close to the work they describe. Factories receive the session-owned runtime explicitly:

export const audioKeys = defineKeys({
	availability: (id: string, blobId: string, uploadedAt: string | null) =>
		['audio', 'availability', id, blobId, uploadedAt] as const,
});

export function createAudioQueries({ defineQuery }: WhisperingQueryRuntime) {
	return {
		availability: (recording: Accessor<Recording>) =>
			defineQuery({
				queryKey: audioKeys.availability(
					recording().id,
					recording().audioBlobId,
					recording().uploadedAt,
				),
				queryFn: () => getRecordingAudioAvailability(recording()),
			}),
	};
}

Rules:

  • Export *Keys = defineKeys({ ... }) beside the adapter or state module that owns the work.
  • Static keys do not need as const; key factories use as const when literal positions matter.
  • Keep keys in the owning module unless another layer needs the same fallback identity.
  • Inline small single-use input objects. Name an input type only when it is reused, exported, large enough to obscure the function, or carries domain meaning. Put named input types immediately before the adapter namespace that uses them.
  • Keep adapter-local defineErrors namespaces local unless another module needs to name that exact union.

Adapter Boundary: Queries vs Operations

Use $lib/queries as the shared TanStack observation surface. It may wrap a direct service/state call, or a $lib/operations entry point when UI needs shared mutation identity: multiple consumers, cache invalidation, optimistic updates, useIsMutating, or a named mutation key over that operation.

Keep orchestration in $lib/operations: delivery, reporting, sounds, analytics, clipboard writes, and multi-step workflows. Do not promote a one-component operation into $lib/queries merely to observe local pending state. The svelte skill owns the component's choice between local createMutation and direct await.

Dependency Direction

UI -> operations/* -> services/* + state/* + $lib/tauri
UI -> queries/*    -> services/* or operations/*, plus narrow state reads/writes for observed lifecycle

Query modules receive the session-owned query runtime and import services, state, or operations. They do not import sibling query modules just to sequence work; cross-adapter coordination belongs in operations.

Error Flow

In Whispering, service and operation errors are already tagged errors. Query adapters pass them through. The UI/report boundary decides how to present them.

Service / Operation       ->  Query Adapter     ->  UI / Report
TaggedError<'Name'>           same error            report.error({ cause: error })

Only define a query-local error when the adapter itself discovers a failure that no lower layer can own, such as a missing recording lookup before calling an operation.

Reactive And Imperative Use

Query-layer adapters provide reactive hook usage and explicit imperative usage.

Reactive Interface: .options

Shared query adapters expose .options as a static object. Svelte hooks read it inside an accessor:

<script lang="ts">
	import { createQuery, createMutation } from '@tanstack/svelte-query';
	import { getWhisperingQueries } from '$lib/whispering/context';

	const queries = getWhisperingQueries();
	const availability = createQuery(() =>
		queries.audio.availability(() => recording).options,
	);

	const transcribeRecording = createMutation(
		() => queries.transcription.transcribeRecording.options,
	);
</script>

{#if availability.isPending}
	<Spinner />
{:else if availability.error !== null}
	<Error message={availability.error.message} />
{:else}
	<AvailabilityBadge value={availability.data} />
{/if}

Imperative Interface: Queries Choose Cache Policy, Mutations Are Callable

Use outside component context, or whenever the caller needs a direct Result:

// In an event handler or workflow
async function handleDownload(recording: Recording) {
	const { error } = await queries.download.downloadRecording(recording);
	if (error !== null) {
		report.error({ cause: error });
		return;
	}
	report.success({ title: 'Recording downloaded' });
}

// In a sequential workflow
async function stopAndTranscribe(toastId: string) {
	const { data: url, error: playbackUrlError } =
		await queries.audio.availability(() => recording).fetch();

	if (playbackUrlError !== null) {
		report.error({ cause: playbackUrlError });
		return;
	}

	// Continue with transcription...
}

Use .fetch() when TanStack should evaluate the query's normal staleness policy: fresh cached data may still be returned without a request. Use .ensure() when any cached data is acceptable and fetching is only required when the cache is empty.

When to Use Each

Adapter surfacePattern
Shared reactive querycreateQuery(() => queries.thing.options)
Shared reactive mutationcreateMutation(() => queries.thing.options)
Imperative query readqueries.thing(...).fetch() or queries.thing(...).ensure()
Imperative mutationqueries.thing(input)

For local component operation placement and lifecycle decisions, use the svelte skill's mutation guidance.

Key Rules

  1. Use defineKeys for shared cache identity - Export the key map beside the owner
  2. Use .options (no parentheses) - It's a static object, wrap in accessor for Svelte
  3. Do not translate tagged errors by default - Pass service/operation errors through to the report boundary
  4. Services receive explicit app inputs - The consuming edge injects settings and device config
  5. Keep component lifecycle policy in svelte - This skill owns shared adapter shape and cache behavior
  6. Update cache deliberately - Use optimistic writes only when the cache owner and rollback path are explicit; otherwise invalidate or refetch

References

Load these on demand based on what you're working on:

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)12moNo flagsAdvanced
frontend-api-integration-patterns03moReviewIntermediate
zustand1132moNo flagsIntermediate
accessibility-compliance452moNo 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