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

index.tsx

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