Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

liaoliao666-react-query-kit.md

79 lines2.0 KB

1---
2id: liaoliao666-react-query-kit
3title: React Query Kit
4---
5​
6πŸ•ŠοΈ A toolkit for ReactQuery that makes ReactQuery hooks reusable and typesafe
7​
8## what do you benefit from it
9​
10- Make `queryKey` strongly related with `queryFn`
11- Manage `queryKey` in a type-safe way
12- Generate a custom ReactQuery hook quickly
13- Make `queryClient`'s operations clearly associated with custom ReactQuery hooks
14- Set defaultOptions for custom ReactQuery hooks easier and clearer
15​
16## Installation
17​
18This module is distributed via [NPM](https://www.npmjs.com/package/react-query-kit) and
19should be installed as one of your project's `dependencies`:
20​
21```bash
22$ npm i react-query-kit
23# or
24$ pnpm add react-query-kit
25# or
26$ yarn add react-query-kit
27```
28​
29## Quick start with nextjs
30​
31[CodeSandbox](https://codesandbox.io/s/example-react-query-kit-nextjs-uldl88)
32​
33```tsx
34import { QueryClient, dehydrate } from '@tanstack/react-query'
35import { createQuery } from 'react-query-kit'
36​
37type Response = { title: string; content: string }
38type Variables = { id: number }
39​
40const usePost = createQuery<Response, Variables, Error>({
41 primaryKey: '/posts',
42 queryFn: ({ queryKey: [primaryKey, variables] }) => {
43 // primaryKey equals to '/posts'
44 return fetch(`${primaryKey}/${variables.id}`).then(res => res.json())
45 },
46 suspense: true
47})
48​
49const variables = { id: 1 }
50​
51export default function Page() {
52 // queryKey equals to ['/posts', { id: 1 }]
53 const { data } = usePost({ variables, suspense: true })
54​
55 return (
56 <div>
57 <div>{data?.title}</div>
58 <div>{data?.content}</div>
59 </div>
60 )
62​
63console.log(usePost.getKey()) // ['/posts']
64console.log(usePost.getKey(variables)) // ['/posts', { id: 1 }]
65​
66export async function getStaticProps() {
67 const queryClient = new QueryClient()
68​
69 await queryClient.prefetchQuery(usePost.getKey(variables), usePost.queryFn)
70​
71 return {
72 props: {
73 dehydratedState: dehydrate(queryClient),
74 },
75 }
77```
78​
79Check the complete documentation on [GitHub](https://github.com/liaoliao666/react-query-kit).