Open History to see the last commit
1import {
2 QueryClientProvider,
3 dehydrate,
4 hydrate,
5 noop,
6} from '@tanstack/preact-query'
7import { PreactQueryDevtools } from '@tanstack/preact-query-devtools'
8import { uneval } from 'devalue'
9import { renderToString } from 'preact-render-to-string'
10import App from './App'
11import { makeQueryClient } from './makeQueryClient'
12import { postsQueries } from './services/posts/queries'
13import { usersQueries } from './services/users/queries'
14β
15export async function render() {
16 // The prefetching client: only used to fetch and dehydrate
17 const prefetchClient = makeQueryClient()
18β
19 // The posts are critical content: without `.catch(noop)`, a failed fetch
20 // throws here and the server responds with an error status
21 const posts = await prefetchClient.query(postsQueries.list())
22β
23 // The author depends on the first post, so prefetch it once its id is known.
24 // It's not critical: on failure it's left out of the dehydrated state and
25 // fetched again on the client
26 const authorId = posts[0]?.userId
27 if (authorId) {
28 await prefetchClient.query(usersQueries.detail(authorId)).catch(noop)
29 }
30β
31 const dehydratedState = dehydrate(prefetchClient)
32β
33 // The render client: hydrated with the same state, used for renderToString
34 const renderClient = makeQueryClient()
35 hydrate(renderClient, dehydratedState)
36β
37 const html = renderToString(
38 <QueryClientProvider client={renderClient}>
39 <App />
40 <PreactQueryDevtools />
41 </QueryClientProvider>,
42 )
43β
44 // `uneval` escapes the state so it can't break out of the <script> tag
45 return { html, state: uneval(dehydratedState) }
46}