Skip to Content
onedef

TanStack Query

Query keys, mutations and cache invalidation, worked out from the contract.

createQueryUtils takes the contract and a typed client (the same client the rest of your app uses; see Clients and transports):

lib/query.ts
import { createClient } from 'onedef'
import { rpc } from '@onedef/orpc/client'
import { createQueryUtils } from '@onedef/query'
import { contract } from './contract'

const api = createClient(contract, rpc({ url: '/api' }))

export const q = createQueryUtils(contract, api)

Then, in any component:

const song = useQuery(q.songs.get.queryOptions({ slug }))
const rename = useMutation(q.songs.rename.mutationOptions())

rename.mutate({ slug, title: 'La Vie en rose' })
// songs.get for this slug updates from the result; songs.list refetches

You never write a query key or an onSuccess refresh:

  • Keys come from the contract: ['onedef', service, op, input].
  • A mutation invalidates the reads of its service (and of any service it names in affects).
  • An action that returns the object (output is the collection's fields) writes the result straight into the get cache, so the screen updates without a refetch.
  • A delete removes the object from the cache.

Paginated lists

const pages = useInfiniteQuery(q.songs.list.infiniteQueryOptions({ q: 'piaf' }))

This works with lists declared with paginate: 'cursor'.

Server-rendered data

Pass what the server already fetched as initialData:

useQuery({ ...q.songs.get.queryOptions({ slug }), initialData: initial })

The React, Vue, Solid and Svelte adapters of TanStack Query v5 all work.

On this page