File size: 2,665 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
'use client'

import {
  defaultShouldDehydrateQuery,
  dehydrate,
  hydrate,
  isServer,
  useQueryClient,
} from '@tanstack/react-query'
import * as React from 'react'
import { createHydrationStreamProvider } from './HydrationStreamProvider'
import type { HydrationStreamProviderProps } from './HydrationStreamProvider'
import type {
  DehydrateOptions,
  DehydratedState,
  HydrateOptions,
  QueryClient,
} from '@tanstack/react-query'

const stream = createHydrationStreamProvider<DehydratedState>()

/**
 * This component is responsible for:
 * - hydrating the query client on the server
 * - dehydrating the query client on the server
 */
export function ReactQueryStreamedHydration(props: {
  children: React.ReactNode
  queryClient?: QueryClient
  nonce?: string
  options?: {
    hydrate?: HydrateOptions
    dehydrate?: DehydrateOptions
  }
  transformer?: HydrationStreamProviderProps<DehydratedState>['transformer']
}) {
  const queryClient = useQueryClient(props.queryClient)

  /**
   * We need to track which queries were added/updated during the render
   */
  const [trackedKeys] = React.useState(() => new Set<string>())

  // <server only>
  if (isServer) {
    // Do we need to care about unsubscribing? I don't think so to be honest
    queryClient.getQueryCache().subscribe((event) => {
      switch (event.type) {
        case 'added':
        case 'updated':
          // console.log('tracking', event.query.queryHash, 'b/c of a', event.type)
          trackedKeys.add(event.query.queryHash)
      }
    })
  }
  // </server only>

  return (
    <stream.Provider
      // Happens on server:
      onFlush={() => {
        /**
         * Dehydrated state of the client where we only include the queries that were added/updated since the last flush
         */
        const shouldDehydrate =
          props.options?.dehydrate?.shouldDehydrateQuery ??
          defaultShouldDehydrateQuery

        const dehydratedState = dehydrate(queryClient, {
          ...props.options?.dehydrate,
          shouldDehydrateQuery(query) {
            return trackedKeys.has(query.queryHash) && shouldDehydrate(query)
          },
        })
        trackedKeys.clear()

        if (!dehydratedState.queries.length) {
          return []
        }

        return [dehydratedState]
      }}
      // Happens in browser:
      onEntries={(entries) => {
        for (const hydratedState of entries) {
          hydrate(queryClient, hydratedState, props.options?.hydrate)
        }
      }}
      // Handle BigInts etc using superjson
      transformer={props.transformer}
      nonce={props.nonce}
    >
      {props.children}
    </stream.Provider>
  )
}