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

HydrationStreamProvider.tsx

190 lines5.4 KB

1'use client'
2​
3import { isServer } from '@tanstack/react-query'
4import { useServerInsertedHTML } from 'next/navigation'
5import * as React from 'react'
6import { htmlEscapeJsonString } from './htmlescape'
7​
8const serializedSymbol = Symbol('serialized')
9​
10interface DataTransformer {
11 serialize: (object: any) => any
12 deserialize: (object: any) => any
14​
15type Serialized<TData> = unknown & {
16 [serializedSymbol]: TData
18​
19interface TypedDataTransformer<TData> {
20 serialize: (obj: TData) => Serialized<TData>
21 deserialize: (obj: Serialized<TData>) => TData
23​
24interface HydrationStreamContext<TShape> {
25 id: string
26 stream: {
27 /**
28 * **Server method**
29 * Push a new entry to the stream
30 * Will be ignored on the client
31 */
32 push: (...shape: Array<TShape>) => void
33 }
35​
36export interface HydrationStreamProviderProps<TShape> {
37 children: React.ReactNode
38 /**
39 * Optional transformer to serialize/deserialize the data
40 * Example devalue, superjson et al
41 */
42 transformer?: DataTransformer
43 /**
44 * **Client method**
45 * Called in the browser when new entries are received
46 */
47 onEntries: (entries: Array<TShape>) => void
48 /**
49 * **Server method**
50 * onFlush is called on the server when the cache is flushed
51 */
52 onFlush?: () => Array<TShape>
53 /**
54 * A nonce that'll allow the inline script to be executed when Content Security Policy is enforced
55 */
56 nonce?: string
58​
59export function createHydrationStreamProvider<TShape>() {
60 const context = React.createContext<HydrationStreamContext<TShape>>(
61 null as any,
62 )
63 /**
64​
65 * 1. (Happens on server): `useServerInsertedHTML()` is called **on the server** whenever a `Suspense`-boundary completes
66 * - This means that we might have some new entries in the cache that needs to be flushed
67 * - We pass these to the client by inserting a `<script>`-tag where we do `window[id].push(serializedVersionOfCache)`
68 * 2. (Happens in browser) In `useEffect()`:
69 * - We check if `window[id]` is set to an array and call `push()` on all the entries which will call `onEntries()` with the new entries
70 * - We replace `window[id]` with a `push()`-method that will be called whenever new entries are received
71 **/
72 function UseClientHydrationStreamProvider(props: {
73 children: React.ReactNode
74 /**
75 * Optional transformer to serialize/deserialize the data
76 * Example devalue, superjson et al
77 */
78 transformer?: DataTransformer
79 /**
80 * **Client method**
81 * Called in the browser when new entries are received
82 */
83 onEntries: (entries: Array<TShape>) => void
84 /**
85 * **Server method**
86 * onFlush is called on the server when the cache is flushed
87 */
88 onFlush?: () => Array<TShape>
89 /**
90 * A nonce that'll allow the inline script to be executed when Content Security Policy is enforced
91 */
92 nonce?: string
93 }) {
94 // unique id for the cache provider
95 const id = `__RQ${React.useId()}`
96 const idJSON = htmlEscapeJsonString(JSON.stringify(id))
97​
98 const [transformer] = React.useState(
99 () =>
100 (props.transformer ?? {
101 // noop
102 serialize: (obj: any) => obj,
103 deserialize: (obj: any) => obj,
104 }) as unknown as TypedDataTransformer<TShape>,
105 )
106​
107 // <server stuff>
108 const [stream] = React.useState<Array<TShape>>(() => {
109 if (!isServer) {
110 return {
111 push() {
112 // no-op on the client
113 },
114 } as unknown as Array<TShape>
115 }
116 return []
117 })
118 const count = React.useRef(0)
119 useServerInsertedHTML(() => {
120 // This only happens on the server
121 stream.push(...(props.onFlush?.() ?? []))
122​
123 if (!stream.length) {
124 return null
125 }
126 // console.log(`pushing ${stream.length} entries`)
127 const serializedCacheArgs = stream
128 .map((entry) => transformer.serialize(entry))
129 .map((entry) => JSON.stringify(entry))
130 .join(',')
131​
132 // Flush stream
133 stream.length = 0
134​
135 const html: Array<string> = [
136 `window[${idJSON}] = window[${idJSON}] || [];`,
137 `window[${idJSON}].push(${htmlEscapeJsonString(serializedCacheArgs)});`,
138 ]
139 return (
140 <script
141 key={count.current++}
142 nonce={props.nonce}
143 dangerouslySetInnerHTML={{
144 __html: html.join(''),
145 }}
146 />
147 )
148 })
149 // </server stuff>
150​
151 // <client stuff>
152 // Setup and run the onEntries handler on the client only, but do it during
153 // the initial render so children have access to the data immediately
154 // This is important to avoid the client suspending during the initial render
155 // if the data has not yet been hydrated.
156 if (!isServer) {
157 const win = window as any
158 if (!win[id]?.initialized) {
159 // Client: consume cache:
160 const onEntries = (...serializedEntries: Array<Serialized<TShape>>) => {
161 const entries = serializedEntries.map((serialized) =>
162 transformer.deserialize(serialized),
163 )
164 props.onEntries(entries)
165 }
166​
167 const winStream: Array<Serialized<TShape>> = win[id] ?? []
168​
169 onEntries(...winStream)
170​
171 win[id] = {
172 initialized: true,
173 push: onEntries,
174 }
175 }
176 }
177 // </client stuff>
178​
179 return (
180 <context.Provider value={{ stream, id }}>
181 {props.children}
182 </context.Provider>
183 )
184 }
185​
186 return {
187 Provider: UseClientHydrationStreamProvider,
188 context,
189 }