@central-kits/tanstack-serverfn-to-query
v0.1.0
Published
useQuery and useMutation hooks that take a TanStack Start server function and build its query key, query function and input type for you
Maintainers
Readme
@central-kits/tanstack-serverfn-to-query
useQuery and useMutation for TanStack Start server functions. Pass the server function, and the package builds the rest:
- the query key:
[serverFn.url], or[serverFn.url, input]when there is input - the query / mutation function:
serverFn({ data: input }), with React Query's abortsignalfor queries - the input type: read from the server function's validators (its own and its middleware's), so no schema import is needed
Every other option is the native React Query one, and the hooks return the native results.
npm install @central-kits/tanstack-serverfn-to-queryPeer dependencies: @tanstack/react-query and @tanstack/react-start.
Exports
| Export | Returns |
| --- | --- |
| useServerFnQuery | Native useQuery result |
| useServerFnMutation | Native useMutation result |
| serverFnQueryOptions | Native query options, for APIs taking options instead of the hook |
| serverFnQueryKey | The query key. Without input, the prefix of every input's key |
| serverFnMutationKey | The mutation key |
Usage
const query = useServerFnQuery({
serverFn: getOrders,
input: { page: 1 }, // typed from getOrders' validators, omitted when it has none
// Any native useQuery option
})
const mutation = useServerFnMutation({
serverFn: updateOrder,
// Any native useMutation option
})
mutation.mutate({ id: '1', status: 'SHIPPED' }) // typed from updateOrder's validators
useSuspenseQuery(serverFnQueryOptions({ serverFn: getOrders, input: { page: 1 } }))
client.invalidateQueries({ queryKey: serverFnQueryKey(getOrders) })
useMutationState({ filters: { mutationKey: serverFnMutationKey(updateOrder) } })How keys are built
The first key item is the server function's url (/_serverFn/<id>). The TanStack Start compiler creates the id per server function at build time: a readable base64 of the file path and export name in dev, a SHA-256 hash in production builds. It is the same on the server and in the browser, so SSR-hydrated cache entries match. The package hashes nothing itself; the input stays a plain second item, so prefix matching (serverFnQueryKey(getOrders)) works.
Keys can't be set by hand, by design.
