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

main.ts

63 lines1.5 KB

1import '@lit-labs/ssr-client/lit-element-hydrate-support.js'
2​
3import { QueryClient, hydrate, type DehydratedState } from '@tanstack/lit-query'
4import { QUERY_STALE_TIME } from './api.js'
5​
6type HydratableSsrApp = HTMLElement & {
7 queryClient?: QueryClient
8}
9​
10function createQueryClient(): QueryClient {
11 return new QueryClient({
12 defaultOptions: {
13 queries: {
14 retry: false,
15 staleTime: QUERY_STALE_TIME,
16 },
17 },
18 })
20​
21function readDehydratedState(): DehydratedState {
22 const stateElement = document.getElementById('__QUERY_STATE__')
23 if (!stateElement) {
24 throw new Error('Missing dehydrated state script.')
25 }
26​
27 const stateText = stateElement.textContent?.trim() ?? 'null'
28 return JSON.parse(stateText) as DehydratedState
30​
31async function bootstrap() {
32 if (document.readyState === 'loading') {
33 await new Promise<void>((resolve) => {
34 document.addEventListener('DOMContentLoaded', () => resolve(), {
35 once: true,
36 })
37 })
38 }
39​
40 const appElement = document.querySelector(
41 'ssr-app',
42 ) as HydratableSsrApp | null
43 if (!appElement) {
44 throw new Error('Expected the SSR app element to exist before hydration.')
45 }
46​
47 const queryClient = createQueryClient()
48 queryClient.mount()
49 hydrate(queryClient, readDehydratedState())
50 appElement.queryClient = queryClient
51​
52 window.addEventListener(
53 'pagehide',
54 () => {
55 queryClient.unmount()
56 },
57 { once: true },
58 )
59​
60 await import('./app.js')
62​
63void bootstrap()