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

main.ts

64 lines1.5 KB

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