diff --git a/.changeset/soft-rivers-hydrate.md b/.changeset/soft-rivers-hydrate.md new file mode 100644 index 00000000000..d32d7564397 --- /dev/null +++ b/.changeset/soft-rivers-hydrate.md @@ -0,0 +1,5 @@ +--- +'@tanstack/query-core': patch +--- + +Type hydration input as a partial dehydrated state so omitted mutation and query collections are supported. diff --git a/packages/query-core/src/__tests__/hydration.test.tsx b/packages/query-core/src/__tests__/hydration.test.tsx index 6b874c42c49..8a8d1db3628 100644 --- a/packages/query-core/src/__tests__/hydration.test.tsx +++ b/packages/query-core/src/__tests__/hydration.test.tsx @@ -676,22 +676,13 @@ describe('dehydration and rehydration', () => { consoleMock.mockRestore() }) - it('should not hydrate if the hydratedState is null or is not an object', () => { - const queryCache = new QueryCache() - const queryClient = new QueryClient({ queryCache }) - - expect(() => hydrate(queryClient, null)).not.toThrow() - expect(() => hydrate(queryClient, 'invalid')).not.toThrow() - - queryClient.clear() - }) - it('should support hydratedState with undefined queries and mutations', () => { const queryCache = new QueryCache() const queryClient = new QueryClient({ queryCache }) + expect(() => hydrate(queryClient, { mutations: [] })).not.toThrow() expect(() => hydrate(queryClient, {})).not.toThrow() - expect(() => hydrate(queryClient, {})).not.toThrow() + expect(() => hydrate(queryClient, { queries: [] })).not.toThrow() queryClient.clear() }) diff --git a/packages/query-core/src/hydration.ts b/packages/query-core/src/hydration.ts index 03106ebab31..9a4ca3f8b01 100644 --- a/packages/query-core/src/hydration.ts +++ b/packages/query-core/src/hydration.ts @@ -193,25 +193,16 @@ export function dehydrate( export function hydrate( client: QueryClient, - dehydratedState: unknown, + dehydratedState: Partial, options?: HydrateOptions, ): void { - if (typeof dehydratedState !== 'object' || dehydratedState === null) { - return - } - const mutationCache = client.getMutationCache() const queryCache = client.getQueryCache() const deserializeData = options?.defaultOptions?.deserializeData ?? client.getDefaultOptions().hydrate?.deserializeData - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - const mutations = (dehydratedState as DehydratedState).mutations || [] - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - const queries = (dehydratedState as DehydratedState).queries || [] - - mutations.forEach(({ state, ...mutationOptions }) => { + dehydratedState.mutations?.forEach(({ state, ...mutationOptions }) => { mutationCache.build( client, { @@ -223,7 +214,7 @@ export function hydrate( ) }) - queries.forEach( + dehydratedState.queries?.forEach( ({ queryKey, state,