Open History to see the last commit
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 })
20}
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
30}
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')
62}
63β
64void bootstrap()