File size: 2,532 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { notifyManager, useQuery } from '@tanstack/solid-query'
import { createSignal } from 'solid-js'
import { QueryBoundary } from '~/components/query-boundary'

function sleep(milliseconds: number) {
  return new Promise((res) => setTimeout(res, milliseconds))
}

function spin(milliseconds: number) {
  const start = performance.now()
  while (performance.now() - start <= milliseconds) {
    // do nothing
  }
}

async function sayHello(name: string) {
  console.info('[api] sayHello.start')

  await sleep(500)

  // make the layout shift more obvious, it doesn't always happen
  console.time('[api] sayHello.spin')
  spin(20)
  console.timeEnd('[api] sayHello.spin')

  console.info('[api] sayHello.end')
  return `Hello ${name}`
}

export default function BatchMethods() {
  const [count, setCount] = createSignal(0)

  const hello = useQuery(() => ({
    queryKey: ['hello', count()] as const,
    queryFn: ({ queryKey: [_, count] }) => sayHello(`solid ${count}`),
  }))

  return (
    <div>
      <select
        value="timer"
        ref={(el) => (el.value = 'timer')} // browser caches form input
        onInput={(e) => {
          const type = e.currentTarget.value
          if (type === 'raf') notifyManager.setScheduler(requestAnimationFrame)
          if (type === 'tick') notifyManager.setScheduler(queueMicrotask)
          if (type === 'timer')
            notifyManager.setScheduler((cb) => setTimeout(cb, 0))
        }}
      >
        <option value="raf">requestAnimationFrame</option>
        <option value="timer">setTimeout</option>
        <option value="tick">queueMicrotick</option>
      </select>
      <button class="increment" onClick={() => setCount((x) => x + 1)}>
        Clicks: {count()}
      </button>
      <p>
        <QueryBoundary loadingFallback={'Loading...'} query={hello}>
          {(data) => <div style={{ 'background-color': 'aqua' }}>{data}</div>}
        </QueryBoundary>
      </p>
      <div style={{ 'background-color': 'red' }}>
        Something below to demonstrate layout shift
      </div>
      <p>
        Due to the way solidjs handles updates, sometimes the updating of a
        query results in DOM modifications triggering a rerender twice. This is
        perceived as a glitch in the layout of the webpage that usually lasts
        for one frame. By using another batching strategy in the browser,
        instead of the default setTimeout one, we can mitigate this issue. Try
        out requestAnimationFrame or queueMicrotick.
      </p>
    </div>
  )
}