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

index.tsx

150 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, Show, Switch, createSignal } from 'solid-js'
9import { render } from '@solidjs/web'
10import type { Setter } from 'solid-js'
11import type { QueryFunction } from '@tanstack/solid-query'
12​
13// Define a default query function that will receive the query key
14const defaultQueryFn: QueryFunction<unknown> = async ({ queryKey }) => {
15 const response = await fetch(
16 `https://jsonplaceholder.typicode.com${queryKey[0]}`,
17 {
18 method: 'GET',
19 },
20 )
21 return response.json()
23​
24// provide the default query function to your app via the query client
25const queryClient = new QueryClient({
26 defaultOptions: {
27 queries: {
28 queryFn: defaultQueryFn,
29 },
30 },
31})
32​
33function App() {
34 const [postId, setPostId] = createSignal(-1)
35​
36 return (
37 <QueryClientProvider client={queryClient}>
38 <SolidQueryDevtools />
39 <p>
40 As you visit the posts below, you will notice them in a loading state
41 the first time you load them. However, after you return to this list and
42 click on any posts you have already visited again, you will see them
43 load instantly and background refresh right before your eyes!{' '}
44 <strong>
45 (You may need to throttle your network speed to simulate longer
46 loading sequences)
47 </strong>
48 </p>
49 <Loading fallback={<div>Loading...</div>}>
50 <Show when={postId() > -1} fallback={<Posts setPostId={setPostId} />}>
51 <Post postId={postId()} setPostId={setPostId} />
52 </Show>
53 </Loading>
54 </QueryClientProvider>
55 )
57​
58function Posts(props: { setPostId: Setter<number> }) {
59 // All you have to do now is pass a key!
60 const state = useQuery<any[]>(() => ({ queryKey: ['/posts'] }))
61​
62 return (
63 <div>
64 <h1>Posts</h1>
65 <div>
66 <Switch>
67 <Match when={state.status === 'pending'}>Loading...</Match>
68 <Match when={state.status === 'error'}>
69 <span>Error: {(state.error as Error).message}</span>
70 </Match>
71 <Match when={state.data !== undefined}>
72 <>
73 <div>
74 <For each={state.data}>
75 {(postAccessor) => {
76 const post =
77 typeof postAccessor === 'function'
78 ? (postAccessor as any)()
79 : postAccessor
80 return (
81 <p>
82 <a
83 onClick={() => props.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(['post', post.id])
89 ? {
90 'font-weight': 'bold',
91 color: 'green',
92 }
93 : {}
94 }
95 >
96 {post.title}
97 </a>
98 </p>
99 )
100 }}
101 </For>
102 </div>
103 <div>{state.isFetching ? 'Background Updating...' : ' '}</div>
104 </>
105 </Match>
106 </Switch>
107 </div>
108 </div>
109 )
111​
112function Post(props: { postId: number; setPostId: Setter<number> }) {
113 // You can even leave out the queryFn and just go straight into options
114 const state = useQuery<any>(() => ({
115 queryKey: [`/posts/${props.postId}`],
116 enabled: !!props.postId,
117 }))
118​
119 return (
120 <div>
121 <div>
122 <a onClick={() => props.setPostId(-1)} href="#">
123 Back
124 </a>
125 </div>
126 <Switch>
127 <Match when={!props.postId || state.status === 'pending'}>
128 Loading...
129 </Match>
130 <Match when={state.status === 'error'}>
131 <span>Error: {(state.error as Error).message}</span>
132 </Match>
133 <Match when={state.data !== undefined}>
134 <>
135 <h1>{state.data.title}</h1>
136 <div>
137 <p>{state.data.body}</p>
138 </div>
139 <div>{state.isFetching ? 'Background Updating...' : ' '}</div>
140 </>
141 </Match>
142 </Switch>
143 </div>
144 )
146​
147const root = document.getElementById('root')
148if (!root) throw new Error('Missing #root element')
149​
150render(() => <App />, root)