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

index.tsx

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