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

index.tsx

163 lines4.5 KB

1/* @refresh reload */
2import {
3 QueryClient,
4 QueryClientProvider,
5 useQuery,
6} from '@tanstack/solid-query'
7import { SolidQueryDevtools } from '@tanstack/solid-query-devtools'
8import { For, Loading, Match, Switch, createSignal } from 'solid-js'
9import { render } from '@solidjs/web'
10import type { Component, Setter } from 'solid-js'
11​
12const queryClient = new QueryClient({
13 defaultOptions: {
14 queries: {
15 gcTime: 1000 * 60 * 60 * 24, // 24 hours
16 },
17 },
18})
19​
20type Post = {
21 id: number
22 title: string
23 body: string
25​
26function createPosts() {
27 return useQuery(() => ({
28 queryKey: ['posts'],
29 queryFn: async (): Promise<Array<Post>> => {
30 const response = await fetch('https://jsonplaceholder.typicode.com/posts')
31 return await response.json()
32 },
33 }))
35​
36function Posts(props: { setPostId: Setter<number> }) {
37 const state = createPosts()
38​
39 return (
40 <div>
41 <h1>Posts</h1>
42 <div>
43 <Switch>
44 <Match when={state.status === 'pending'}>Loading...</Match>
45 <Match when={state.status === 'error'}>
46 <span>Error: {(state.error as Error).message}</span>
47 </Match>
48 <Match when={state.data !== undefined}>
49 <>
50 <div>
51 <For each={state.data}>
52 {(post) => {
53 const p =
54 typeof post === 'function' ? (post as () => Post)() : post
55 return (
56 <p>
57 <a
58 onClick={() => props.setPostId(p.id)}
59 href="#"
60 style={
61 // We can access the query data here to show bold links for
62 // ones that are cached
63 queryClient.getQueryData(['post', p.id])
64 ? {
65 'font-weight': 'bold',
66 color: 'green',
67 }
68 : {}
69 }
70 >
71 {p.title}
72 </a>
73 </p>
74 )
75 }}
76 </For>
77 </div>
78 <div>{state.isFetching ? 'Background Updating...' : ' '}</div>
79 </>
80 </Match>
81 </Switch>
82 </div>
83 </div>
84 )
86​
87const getPostById = async (id: number): Promise<Post> => {
88 const response = await fetch(
89 `https://jsonplaceholder.typicode.com/posts/${id}`,
90 )
91 return await response.json()
93​
94function createPost(postId: number) {
95 return useQuery(() => ({
96 queryKey: ['post', postId],
97 queryFn: () => getPostById(postId),
98 enabled: !!postId,
99 }))
101​
102function Post(props: { postId: number; setPostId: Setter<number> }) {
103 const state = createPost(props.postId)
104​
105 return (
106 <div>
107 <div>
108 <a onClick={() => props.setPostId(-1)} href="#">
109 Back
110 </a>
111 </div>
112 <Switch>
113 <Match when={!props.postId || state.status === 'pending'}>
114 Loading...
115 </Match>
116 <Match when={state.status === 'error'}>
117 <span>Error: {(state.error as Error).message}</span>
118 </Match>
119 <Match when={state.data !== undefined}>
120 <>
121 <h1>{state.data?.title}</h1>
122 <div>
123 <p>{state.data?.body}</p>
124 </div>
125 <div>{state.isFetching ? 'Background Updating...' : ' '}</div>
126 </>
127 </Match>
128 </Switch>
129 </div>
130 )
132​
133const App: Component = () => {
134 const [postId, setPostId] = createSignal(-1)
135​
136 return (
137 <QueryClientProvider client={queryClient}>
138 <SolidQueryDevtools />
139 <p>
140 As you visit the posts below, you will notice them in a loading state
141 the first time you load them. However, after you return to this list and
142 click on any posts you have already visited again, you will see them
143 load instantly and background refresh right before your eyes!{' '}
144 <strong>
145 (You may need to throttle your network speed to simulate longer
146 loading sequences)
147 </strong>
148 </p>
149 <Loading fallback={<div>Loading...</div>}>
150 {postId() > -1 ? (
151 <Post postId={postId()} setPostId={setPostId} />
152 ) : (
153 <Posts setPostId={setPostId} />
154 )}
155 </Loading>
156 </QueryClientProvider>
157 )
159​
160const root = document.getElementById('root')
161if (!root) throw new Error('Missing #root element')
162​
163render(() => <App />, root)