Skip to content

Commit c6e6cdf

Browse files
committed
fix: support infinite cache time when hydrating
1 parent 2207474 commit c6e6cdf

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

src/hydration/hydration.ts

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,22 @@ export interface DehydrateConfig {
2222
shouldDehydrate?: ShouldDehydrateFunction
2323
}
2424

25+
function serializePositiveNumber(value: number): number {
26+
return value === Infinity ? -1 : value
27+
}
28+
29+
function deserializePositiveNumber(value: number): number {
30+
return value === -1 ? Infinity : value
31+
}
32+
2533
// Most config is not dehydrated but instead meant to configure again when
2634
// consuming the de/rehydrated data, typically with useQuery on the client.
2735
// Sometimes it might make sense to prefetch data on the server and include
2836
// in the html-payload, but not consume it on the initial render.
2937
function dehydrateQuery(query: Query): DehydratedQuery {
3038
return {
3139
config: {
32-
cacheTime: query.cacheTime,
40+
cacheTime: serializePositiveNumber(query.cacheTime),
3341
},
3442
data: query.state.data,
3543
queryKey: query.queryKey,
@@ -80,7 +88,9 @@ export function hydrate(cache: QueryCache, dehydratedState: unknown): void {
8088
queryKey: dehydratedQuery.queryKey,
8189
queryHash: dehydratedQuery.queryHash,
8290
options: {
83-
cacheTime: dehydratedQuery.config.cacheTime,
91+
cacheTime: deserializePositiveNumber(
92+
dehydratedQuery.config.cacheTime
93+
),
8494
},
8595
})
8696
cache.add(query)

src/hydration/tests/hydration.test.tsx

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,22 @@ describe('dehydration and rehydration', () => {
8888
hydrationCache.clear()
8989
})
9090

91+
test('should serialize the cacheTime correctly', async () => {
92+
const cache = new QueryCache()
93+
const client = new QueryClient({ cache })
94+
await client.prefetchQuery('string', () => fetchData('string'), {
95+
cacheTime: Infinity,
96+
})
97+
const dehydrated = dehydrate(cache)
98+
const stringified = JSON.stringify(dehydrated)
99+
const parsed = JSON.parse(stringified)
100+
const hydrationCache = new QueryCache()
101+
hydrate(hydrationCache, parsed)
102+
expect(hydrationCache.find('string')?.cacheTime).toBe(Infinity)
103+
cache.clear()
104+
hydrationCache.clear()
105+
})
106+
91107
test('should work with complex keys', async () => {
92108
const cache = new QueryCache()
93109
const client = new QueryClient({ cache })

0 commit comments

Comments
 (0)