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

index.tsx

148 lines3.9 KB

1import {
2 QueryClient,
3 QueryClientProvider,
4 useQuery,
5 useQueryClient,
6} from '@tanstack/preact-query'
7import { PreactQueryDevtools } from '@tanstack/preact-query-devtools'
8import { render } from 'preact'
9import { useState } from 'preact/hooks'
10import type { QueryKey } from '@tanstack/preact-query'
11​
12type Post = {
13 id: number
14 title: string
15 body: string
17​
18// Define a default query function that will receive the query key
19const defaultQueryFn = async ({ queryKey }: { queryKey: QueryKey }) => {
20 const response = await fetch(
21 `https://jsonplaceholder.typicode.com${queryKey[0]}`,
22 )
23 if (!response.ok) throw new Error('Failed to fetch data')
24 return await response.json()
26​
27// provide the default query function to your app via the query client
28const queryClient = new QueryClient({
29 defaultOptions: {
30 queries: {
31 queryFn: defaultQueryFn,
32 },
33 },
34})
35​
36function App() {
37 const [postId, setPostId] = useState(-1)
38​
39 return (
40 <QueryClientProvider client={queryClient}>
41 <p>
42 As you visit the posts below, you will notice them in a loading state
43 the first time you load them. However, after you return to this list and
44 click on any posts you have already visited again, you will see them
45 load instantly and background refresh right before your eyes!{' '}
46 <strong>
47 (You may need to throttle your network speed to simulate longer
48 loading sequences)
49 </strong>
50 </p>
51 {postId > -1 ? (
52 <Post postId={postId} setPostId={setPostId} />
53 ) : (
54 <Posts setPostId={setPostId} />
55 )}
56 <PreactQueryDevtools initialIsOpen />
57 </QueryClientProvider>
58 )
60​
61function Posts({ setPostId }: { setPostId: (postId: number) => void }) {
62 const queryClient = useQueryClient()
63​
64 // All you have to do now is pass a key!
65 const { status, data, error, isFetching } = useQuery<Array<Post>>({
66 queryKey: ['/posts'],
67 })
68​
69 return (
70 <div>
71 <h1>Posts</h1>
72 <div>
73 {status === 'pending' ? (
74 'Loading...'
75 ) : status === 'error' ? (
76 <span>Error: {error.message}</span>
77 ) : (
78 <>
79 <div>
80 {data.map((post) => (
81 <p key={post.id}>
82 <a
83 onClick={() => setPostId(post.id)}
84 href="#"
85 style={
86 // We can use the queryCache here to show bold links for
87 // ones that are cached
88 queryClient.getQueryData([`/posts/${post.id}`])
89 ? {
90 fontWeight: 'bold',
91 color: 'green',
92 }
93 : {}
94 }
95 >
96 {post.title}
97 </a>
98 </p>
99 ))}
100 </div>
101 <div>{isFetching ? 'Background Updating...' : ' '}</div>
102 </>
103 )}
104 </div>
105 </div>
106 )
108​
109function Post({
110 postId,
111 setPostId,
112}: {
113 postId: number
114 setPostId: (postId: number) => void
115}) {
116 // You can even leave out the queryFn and just go straight into options
117 const { status, data, error, isFetching } = useQuery<Post>({
118 queryKey: [`/posts/${postId}`],
119 enabled: !!postId,
120 })
121​
122 return (
123 <div>
124 <div>
125 <a onClick={() => setPostId(-1)} href="#">
126 Back
127 </a>
128 </div>
129 {!postId || status === 'pending' ? (
130 'Loading...'
131 ) : status === 'error' ? (
132 <span>Error: {error.message}</span>
133 ) : (
134 <>
135 <h1>{data.title}</h1>
136 <div>
137 <p>{data.body}</p>
138 </div>
139 <div>{isFetching ? 'Background Updating...' : ' '}</div>
140 </>
141 )}
142 </div>
143 )
145​
146const rootElement = document.getElementById('root')
147if (!rootElement) throw new Error('Missing #root element')
148render(<App />, rootElement)