Define an API shape using `router`
mainThe router function allows you to define the entire shape of your API in a hierarchical structure. You can nest routers to create organized API endpoints. Each node in the router can define queries, infinite queries, or mutations.
Key features:
- Hierarchical Keys: Automatically manages nested query keys.
- Integrated Hooks: Each definition provides ready-to-use hooks like
useQuery,useInfiniteQuery, anduseMutation. - Type Inference: Automatically infers data and variable types from the
fetcherormutationFn.
Common methods available on router nodes:
getKey(variables?): Returns the query key array.getOptions(variables?): Returns TanStack Query options.getFetchOptions(variables?): Returns only the necessary options for fetching (omitsstaleTime,retry, etc.).fetcher(variables?): Returns the fetcher function.
import { router } from 'react-query-kit'
const post = router(`post`, {
byId: router.query({
fetcher: (variables: { id: number }) =>
fetch(`/posts/${variables.id}`).then(res => res.json()),
}),
list: router.infiniteQuery({
fetcher: (_variables, { pageParam }) =>
fetch(`/posts/?cursor=${pageParam}`).then(res => res.json()),
getNextPageParam: lastPage => lastPage.nextCursor,
initialPageParam: 0,
}),
add: router.mutation({
mutationFn: async (variables: { title: string; content: string }) =>
fetch('/posts', {
method: 'POST',
body: JSON.stringify(variables)
}).then(res => res.json()),
}),
// Nesting a router
command: router(`command`, {
report: router.mutation({ mutationFn: ... }),
}),
})
// Usage
post.byId.useQuery({ variables: { id: 1 } })
post.list.useInfiniteQuery()
post.add.useMutation()