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

batch-methods.tsx

77 lines2.5 KB

1import { notifyManager, useQuery } from '@tanstack/solid-query'
2import { createSignal } from 'solid-js'
3import { QueryBoundary } from '~/components/query-boundary'
4​
5function sleep(milliseconds: number) {
6 return new Promise((res) => setTimeout(res, milliseconds))
7}
8​
9function spin(milliseconds: number) {
10 const start = performance.now()
11 while (performance.now() - start <= milliseconds) {
12 // do nothing
13 }
15​
16async function sayHello(name: string) {
17 console.info('[api] sayHello.start')
18​
19 await sleep(500)
20​
21 // make the layout shift more obvious, it doesn't always happen
22 console.time('[api] sayHello.spin')
23 spin(20)
24 console.timeEnd('[api] sayHello.spin')
25​
26 console.info('[api] sayHello.end')
27 return `Hello ${name}`
29​
30export default function BatchMethods() {
31 const [count, setCount] = createSignal(0)
32​
33 const hello = useQuery(() => ({
34 queryKey: ['hello', count()] as const,
35 queryFn: ({ queryKey: [, currentCount] }) =>
36 sayHello(`solid ${currentCount}`),
37 }))
38​
39 return (
40 <div>
41 <select
42 value="timer"
43 ref={(el) => (el.value = 'timer')} // browser caches form input
44 onInput={(e) => {
45 const type = e.currentTarget.value
46 if (type === 'raf') notifyManager.setScheduler(requestAnimationFrame)
47 if (type === 'tick') notifyManager.setScheduler(queueMicrotask)
48 if (type === 'timer')
49 notifyManager.setScheduler((cb) => setTimeout(cb, 0))
50 }}
51 >
52 <option value="raf">requestAnimationFrame</option>
53 <option value="timer">setTimeout</option>
54 <option value="tick">queueMicrotick</option>
55 </select>
56 <button class="increment" onClick={() => setCount((x) => x + 1)}>
57 Clicks: {count()}
58 </button>
59 <p>
60 <QueryBoundary loadingFallback={'Loading...'} query={hello}>
61 {(data) => <div style={{ 'background-color': 'aqua' }}>{data}</div>}
62 </QueryBoundary>
63 </p>
64 <div style={{ 'background-color': 'red' }}>
65 Something below to demonstrate layout shift
66 </div>
67 <p>
68 Due to the way solidjs handles updates, sometimes the updating of a
69 query results in DOM modifications triggering a rerender twice. This is
70 perceived as a glitch in the layout of the webpage that usually lasts
71 for one frame. By using another batching strategy in the browser,
72 instead of the default setTimeout one, we can mitigate this issue. Try
73 out requestAnimationFrame or queueMicrotick.
74 </p>
75 </div>
76 )