Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(hydration): dehydrate.serialize and hydrate.deserialize #7615

Merged
merged 15 commits into from
Jun 29, 2024
1 change: 1 addition & 0 deletions integrations/react-next-15/app/make-query-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export function makeQueryClient() {
return new QueryClient({
defaultOptions: {
hydrate: {
transformData: (data) => tson.deserialize(data),
/**
* Called when the query is rebuilt from a prefetched
* promise, before the query data is put into the cache.
Expand Down
37 changes: 37 additions & 0 deletions packages/query-core/src/__tests__/hydration.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -943,4 +943,41 @@ describe('dehydration and rehydration', () => {

queryClient.clear()
})

test('should transform query data if promise is already resolved', async () => {
const queryClient = createQueryClient({
defaultOptions: {
dehydrate: {
shouldDehydrateQuery: () => true,
},
},
})

const promise = queryClient.prefetchQuery({
queryKey: ['transformedStringToDate'],
queryFn: () => fetchData('2024-01-01T00:00:00.000Z', 0),
})
await sleep(20)
const dehydrated = dehydrate(queryClient)
console.log('de', dehydrated)
juliusmarminge marked this conversation as resolved.
Show resolved Hide resolved

const hydrationClient = createQueryClient({
defaultOptions: {
hydrate: {
transformData: (d) => new Date(d),
transformPromise: (p) => p.then((d) => new Date(d)),
},
},
})

hydrate(hydrationClient, dehydrated)
await promise
await waitFor(() =>
expect(
hydrationClient.getQueryData(['transformedStringToDate']),
).toBeInstanceOf(Date),
)

queryClient.clear()
})
})
5 changes: 5 additions & 0 deletions packages/query-core/src/hydration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export interface DehydrateOptions {

export interface HydrateOptions {
defaultOptions?: {
transformData?: (data: any) => any
transformPromise?: (promise: Promise<any>) => Promise<any>
queries?: QueryOptions
mutations?: MutationOptions<unknown, DefaultError, unknown, unknown>
Expand Down Expand Up @@ -160,6 +161,7 @@ export function hydrate(
}
} else {
// Restore query
const transformData = client.getDefaultOptions().hydrate?.transformData
query = queryCache.build(
client,
{
Expand All @@ -173,6 +175,9 @@ export function hydrate(
// query being stuck in fetching state upon hydration
{
...state,
...('data' in state && {
data: transformData?.(state.data) ?? state.data,
}),
fetchStatus: 'idle',
},
)
Expand Down
Loading