DEV Community

Cover image for Typed query keys for TanStack Query v5: scopes, invalidation and mutations
Amjad Iqbal
Amjad Iqbal

Posted on

Typed query keys for TanStack Query v5: scopes, invalidation and mutations

The gap queryOptions() leaves

TanStack Query v5's queryOptions() keeps a key and its fetcher together. It does not give you a key hierarchy: one place that says which keys exist, how they nest, and which partial key to pass when you invalidate.

Declare a scope once

query-key-kit is a typed query-key factory. createQueryKeys('todos', {...}) takes entries (null, a key tuple, an options object or a function) and returns real query options with a DataTag-branded queryKey [1][2].

Typed scope helpers

  • invalidateScope, refetchScope, cancelScope, removeScope
  • getScopeData and setScopeData, typed by the queries they match
  • createMutationKeys, which keeps mutationFn's own type

Passing todos.detail(1) invalidates detail 1 and its context queries; passing todos invalidates everything under 'todos' [3].

Limits

  • Mutation entries and scopes are rejected by the scope helpers, at compile time and at run time.
  • Tested with React Query and Vue Query; Solid, Svelte and Angular Query have no tests of their own yet.

Install

npm install @amjadiqbal/query-key-kit
Enter fullscreen mode Exit fullscreen mode

MIT licence. Needs TanStack Query v5 and TypeScript 5.0 or newer. Docs and demo | Source on GitHub

References

  1. TanStack Query: Query Keys
  2. TanStack Query: queryOptions
  3. TanStack Query: Query Invalidation

Top comments (0)