diff --git a/.changeset/query-cache-equality.md b/.changeset/query-cache-equality.md new file mode 100644 index 00000000000..3a2a808674f --- /dev/null +++ b/.changeset/query-cache-equality.md @@ -0,0 +1,7 @@ +--- +'@tanstack/query-core': major +--- + +Add optional `equalityFn` and `hashFn` configuration to `QueryCache.queryKey` and `MutationCache.mutationKey` for custom key comparison and hashing. Extend `replaceEqualDeep` with an optional equality function for structural sharing of custom value types. Remove the per-query `queryKeyHashFn` option and the `QueryKeyHashFunction` type. Configure `new QueryCache({ queryKey: { hashFn } })` on the client to customize hashing. To apply different hashes to different queries, branch on the key inside `hashFn` and use `hashKey` for the default. + +Partial key matching now recurses only into plain arrays and objects. Use `equalityFn` to compare values such as `Date` instances. The third argument to `replaceEqualDeep` now accepts an equality function. The recursion depth is managed internally. diff --git a/docs/framework/react/guides/render-optimizations.md b/docs/framework/react/guides/render-optimizations.md index 788ea099008..f31f7a64de8 100644 --- a/docs/framework/react/guides/render-optimizations.md +++ b/docs/framework/react/guides/render-optimizations.md @@ -11,6 +11,23 @@ React Query uses a technique called "structural sharing" to ensure that as many > Note: This optimization only works if the `queryFn` returns JSON compatible data. You can turn it off by setting `structuralSharing: false` globally or on a per-query basis, or you can implement your own structural sharing by passing a function to it. +If your data contains custom value types, you can pass an equality function to `replaceEqualDeep` from your `structuralSharing` function. The previous value is kept when the function returns `true`: + +```tsx +import { replaceEqualDeep, useQuery } from '@tanstack/react-query' + +const equalityFn = (a: unknown, b: unknown) => + a === b || + (a instanceof Date && b instanceof Date && a.getTime() === b.getTime()) + +useQuery({ + queryKey: ['events'], + queryFn: fetchEvents, + structuralSharing: (oldData, newData) => + replaceEqualDeep(oldData, newData, equalityFn), +}) +``` + ### referential identity The top level object returned from `useQuery`, `useInfiniteQuery`, `useMutation` and the Array returned from `useQueries` is **not referentially stable**. It will be a new reference on every render. However, the `data` properties returned from these hooks will be as stable as possible. diff --git a/packages/preact-query/src/__tests__/useQuery.test.tsx b/packages/preact-query/src/__tests__/useQuery.test.tsx index 5f9a025f718..97b3e817d4c 100644 --- a/packages/preact-query/src/__tests__/useQuery.test.tsx +++ b/packages/preact-query/src/__tests__/useQuery.test.tsx @@ -4905,17 +4905,21 @@ describe('useQuery', () => { let hashes = 0 let renders = 0 - function queryKeyHashFn(x: any) { + function hashFn(queryKey: ReadonlyArray) { hashes++ - return JSON.stringify(x) + return JSON.stringify(queryKey) } + queryClient = new QueryClient({ + queryCache: new QueryCache({ queryKey: { hashFn } }), + }) + function Page() { useEffect(() => { renders++ }) - useQuery({ queryKey: key, queryFn: () => 'test', queryKeyHashFn }) + useQuery({ queryKey: key, queryFn: () => 'test' }) return null } @@ -4928,15 +4932,19 @@ describe('useQuery', () => { it('should hash query keys that contain bigints given a supported query hash function', async () => { const key = [createKey(), 1n] - function queryKeyHashFn(x: any) { - return JSON.stringify(x, (_, value) => { + function hashFn(queryKey: ReadonlyArray) { + return JSON.stringify(queryKey, (_, value) => { if (typeof value === 'bigint') return value.toString() return value }) } + queryClient = new QueryClient({ + queryCache: new QueryCache({ queryKey: { hashFn } }), + }) + function Page() { - useQuery({ queryKey: key, queryFn: () => 'test', queryKeyHashFn }) + useQuery({ queryKey: key, queryFn: () => 'test' }) return null } @@ -4944,7 +4952,7 @@ describe('useQuery', () => { await vi.advanceTimersByTimeAsync(0) - const query = queryClient.getQueryCache().get(queryKeyHashFn(key)) + const query = queryClient.getQueryCache().get(hashFn(key)) expect(query?.state.data).toBe('test') }) diff --git a/packages/query-core/src/__tests__/mutationCache.test-d.tsx b/packages/query-core/src/__tests__/mutationCache.test-d.tsx index deb68300b5c..c81da0ce910 100644 --- a/packages/query-core/src/__tests__/mutationCache.test-d.tsx +++ b/packages/query-core/src/__tests__/mutationCache.test-d.tsx @@ -74,9 +74,9 @@ describe('mutationCache', () => { }) describe('MutationCacheConfig', () => { - it('should declare exactly its four callbacks', () => { + it('should declare its key configuration and four callbacks', () => { expectTypeOf().toEqualTypeOf< - 'onError' | 'onSuccess' | 'onMutate' | 'onSettled' + 'mutationKey' | 'onError' | 'onSuccess' | 'onMutate' | 'onSettled' >() }) diff --git a/packages/query-core/src/__tests__/mutationCache.test.tsx b/packages/query-core/src/__tests__/mutationCache.test.tsx index 103f2f08e1e..97f076e7f86 100644 --- a/packages/query-core/src/__tests__/mutationCache.test.tsx +++ b/packages/query-core/src/__tests__/mutationCache.test.tsx @@ -368,6 +368,49 @@ describe('mutationCache', () => { }), ).toStrictEqual(mutation) }) + + it('should use the MutationCache equality function for partial mutation key matching', () => { + const equalityFn = (a: unknown, b: unknown) => + typeof a === 'string' && typeof b === 'string' + ? a.toLowerCase() === b.toLowerCase() + : a === b + const testCache = new MutationCache({ mutationKey: { equalityFn } }) + const testClient = new QueryClient({ mutationCache: testCache }) + const mutation = Mutation.build(testClient, { + mutationKey: ['todos', { status: 'done' }], + mutationFn: () => Promise.resolve(), + }) + + expect( + testCache.find({ + mutationKey: ['TODOS', { status: 'DONE' }], + exact: false, + }), + ).toBe(mutation) + expect( + testCache.findAll({ + mutationKey: ['TODOS', { status: 'DONE' }], + }), + ).toStrictEqual([mutation]) + + testClient.clear() + }) + + it('should use the MutationCache mutation key hash function for exact matching', () => { + const key = ['todos', { status: 'done' }] + const hashFn = vi.fn<() => string>(() => 'custom-hash') + const testCache = new MutationCache({ mutationKey: { hashFn } }) + const testClient = new QueryClient({ mutationCache: testCache }) + const mutation = Mutation.build(testClient, { + mutationKey: key, + mutationFn: () => Promise.resolve(), + }) + + expect(testCache.find({ mutationKey: [...key] })).toBe(mutation) + expect(hashFn).toHaveBeenCalledWith(key) + + testClient.clear() + }) }) describe('findAll', () => { diff --git a/packages/query-core/src/__tests__/query.test.tsx b/packages/query-core/src/__tests__/query.test.tsx index 62eb1943beb..8b09bc4f470 100644 --- a/packages/query-core/src/__tests__/query.test.tsx +++ b/packages/query-core/src/__tests__/query.test.tsx @@ -15,7 +15,7 @@ import { hydrate, noop, } from '..' -import { hashQueryKeyByOptions } from '../utils' +import { hashKeyByOptions } from '../utils' import { mockOnlineManagerIsOnline, setIsServer } from './utils' import type { QueryCacheNotifyEvent, @@ -1359,7 +1359,10 @@ describe('query', () => { const query = new Query({ client: queryClient, queryKey: key, - queryHash: hashQueryKeyByOptions(key), + queryHash: hashKeyByOptions( + key, + queryClient.getQueryCache().config.queryKey, + ), }) query.addObserver(observer) @@ -1392,7 +1395,10 @@ describe('query', () => { const query = new Query({ client: queryClient, queryKey: key, - queryHash: hashQueryKeyByOptions(key), + queryHash: hashKeyByOptions( + key, + queryClient.getQueryCache().config.queryKey, + ), options: { queryFn: () => 'data', initialData: initialDataFn, @@ -1475,7 +1481,10 @@ describe('query', () => { const query = new Query({ client: queryClient, queryKey: key, - queryHash: hashQueryKeyByOptions(key), + queryHash: hashKeyByOptions( + key, + queryClient.getQueryCache().config.queryKey, + ), options: { queryFn }, }) diff --git a/packages/query-core/src/__tests__/queryCache.test-d.tsx b/packages/query-core/src/__tests__/queryCache.test-d.tsx index a06c3574f91..ed85743d72c 100644 --- a/packages/query-core/src/__tests__/queryCache.test-d.tsx +++ b/packages/query-core/src/__tests__/queryCache.test-d.tsx @@ -2,6 +2,7 @@ import { createKey } from '@tanstack/query-test-utils' import { afterEach, beforeEach, describe, expectTypeOf, it } from 'vitest' import { QueryCache, QueryClient } from '..' import type { + CacheKeyConfig, DefaultError, NotifyEvent, NotifyEventType, @@ -77,8 +78,9 @@ describe('queryCache', () => { }) describe('QueryCacheConfig', () => { - it('should declare every callback as optional', () => { + it('should declare every option as optional', () => { expectTypeOf().toEqualTypeOf<{ + queryKey?: CacheKeyConfig onError?: ( error: DefaultError, query: Query, diff --git a/packages/query-core/src/__tests__/queryCache.test.tsx b/packages/query-core/src/__tests__/queryCache.test.tsx index f271bee855b..06a44f75d00 100644 --- a/packages/query-core/src/__tests__/queryCache.test.tsx +++ b/packages/query-core/src/__tests__/queryCache.test.tsx @@ -192,6 +192,30 @@ describe('queryCache', () => { const query = queryCache.find({ queryKey: key, exact: false })! expect(query.state.data).toBe('data1') }) + + it('should use the QueryCache equality function for partial query key matching', () => { + const equalityFn = (a: unknown, b: unknown) => + typeof a === 'string' && typeof b === 'string' + ? a.toLowerCase() === b.toLowerCase() + : a === b + const testCache = new QueryCache({ queryKey: { equalityFn } }) + const testClient = new QueryClient({ queryCache: testCache }) + const query = testClient.getQueryCache().build(testClient, { + queryKey: ['todos', { status: 'done' }], + }) + + expect( + testCache.find({ + queryKey: ['TODOS', { status: 'DONE' }], + exact: false, + }), + ).toBe(query) + expect( + testCache.findAll({ queryKey: ['TODOS', { status: 'DONE' }] }), + ).toStrictEqual([query]) + + testClient.clear() + }) }) describe('findAll', () => { @@ -363,6 +387,59 @@ describe('queryCache', () => { .catch(noop) expect(queryCache.findAll()).toHaveLength(2) }) + + it('should return all the queries when key contains object with an undefined property (#3741)', async () => { + const baseKey = createKey() + + const client = new QueryClient({ + queryCache: new QueryCache({ + queryKey: { + equalityFn: (a, b) => b === undefined || Object.is(a, b), + }, + }), + }) + + const keyForId = (id?: number) => [{ ...baseKey, a: id }] + + await client.query({ queryKey: keyForId(1), queryFn: () => 'data1' }) + await client.query({ + queryKey: keyForId(), + queryFn: () => 'data-nothing', + }) + expect( + client.getQueryCache().findAll({ queryKey: keyForId() }), + ).toHaveLength(2) + }) + + it('should invalidate matching dates (#10982)', async () => { + const client = new QueryClient({ + queryCache: new QueryCache({ + queryKey: { + equalityFn: (a, b) => { + if (a instanceof Date && b instanceof Date) { + return a.toISOString() === b.toISOString() + } + return a === b + }, + }, + }), + }) + + await client.query({ + queryKey: ['report', { from: new Date('2020-01-01') }], + queryFn: () => 'data1', + }) + await client.query({ + queryKey: ['report', { from: new Date('2021-06-25') }], + queryFn: () => 'data2', + }) + + expect( + client.getQueryCache().findAll({ + queryKey: ['report', { from: new Date('2020-01-01') }], + }), + ).toHaveLength(1) + }) }) describe('QueryCacheConfig error callbacks', () => { @@ -451,6 +528,19 @@ describe('queryCache', () => { expect(query.queryHash).toBe(hashKey(key)) }) + it('should use the QueryCache query key hash function', () => { + const key = createKey() + const hashFn = vi.fn<() => string>(() => 'custom-hash') + const testCache = new QueryCache({ queryKey: { hashFn } }) + const testClient = new QueryClient({ queryCache: testCache }) + + const query = testCache.build(testClient, { queryKey: key }) + + expect(query.queryHash).toBe('custom-hash') + expect(testCache.find({ queryKey: key })).toBe(query) + expect(hashFn).toHaveBeenCalledWith(key) + }) + it('should use provided queryHash instead of computing it', () => { const key = createKey() const customHash = 'custom-hash' diff --git a/packages/query-core/src/__tests__/queryClient.test.tsx b/packages/query-core/src/__tests__/queryClient.test.tsx index bafb760ea7a..0d546826e8d 100644 --- a/packages/query-core/src/__tests__/queryClient.test.tsx +++ b/packages/query-core/src/__tests__/queryClient.test.tsx @@ -2,7 +2,9 @@ import { createKey, sleep } from '@tanstack/query-test-utils' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { CancelledError, + MutationCache, MutationObserver, + QueryCache, QueryClient, QueryObserver, dehydrate, @@ -16,7 +18,6 @@ import { mockOnlineManagerIsOnline } from './utils' import type { InfiniteData, Query, - QueryCache, QueryCacheNotifyEvent, QueryFunction, QueryObserverOptions, @@ -105,6 +106,26 @@ describe('queryClient', () => { expect(data).toBe('data') }) + it('should use the QueryCache equality function when matching defaults', () => { + const equalityFn = (a: unknown, b: unknown) => + typeof a === 'string' && typeof b === 'string' + ? a.toLowerCase() === b.toLowerCase() + : a === b + const testClient = new QueryClient({ + queryCache: new QueryCache({ queryKey: { equalityFn } }), + }) + + testClient.setQueryDefaults(['todos', { status: 'done' }], { + staleTime: 1000, + }) + + expect( + testClient.getQueryDefaults(['TODOS', { status: 'DONE' }]), + ).toMatchObject({ staleTime: 1000 }) + + testClient.clear() + }) + it('should not match if the query key is a subset', async () => { const key = createKey() queryClient.setQueryDefaults([key, 'a'], { @@ -216,10 +237,10 @@ describe('queryClient', () => { }).not.toThrow() }) - it('should use default options', () => { + it('should use the configured query cache hash function', () => { const key = createKey() const testClient = new QueryClient({ - defaultOptions: { queries: { queryKeyHashFn: () => 'someKey' } }, + queryCache: new QueryCache({ queryKey: { hashFn: () => 'someKey' } }), }) const testCache = testClient.getQueryCache() testClient.setQueryData(key, 'data') @@ -2730,5 +2751,25 @@ describe('queryClient', () => { mutationOptions2, ) }) + + it('should use the MutationCache equality function when matching defaults', () => { + const equalityFn = (a: unknown, b: unknown) => + typeof a === 'string' && typeof b === 'string' + ? a.toLowerCase() === b.toLowerCase() + : a === b + const testClient = new QueryClient({ + mutationCache: new MutationCache({ mutationKey: { equalityFn } }), + }) + + testClient.setMutationDefaults(['todos', { status: 'done' }], { + retry: false, + }) + + expect( + testClient.getMutationDefaults(['TODOS', { status: 'DONE' }]), + ).toMatchObject({ retry: false }) + + testClient.clear() + }) }) }) diff --git a/packages/query-core/src/__tests__/queryObserver.test-d.tsx b/packages/query-core/src/__tests__/queryObserver.test-d.tsx index 0c65421c852..c8bd3e9eaae 100644 --- a/packages/query-core/src/__tests__/queryObserver.test-d.tsx +++ b/packages/query-core/src/__tests__/queryObserver.test-d.tsx @@ -422,37 +422,6 @@ describe('queryObserver', () => { }) }) - describe('queryKeyHashFn', () => { - it('should type the queryKey given to a queryKeyHashFn', () => { - const key = ['a', 1] as const - - new QueryObserver(queryClient, { - queryKey: key, - queryFn: () => Promise.resolve('data'), - queryKeyHashFn: (queryKeyToHash) => { - expectTypeOf(queryKeyToHash).toEqualTypeOf() - return 'hash' - }, - }) - }) - - it('should only accept a string from a queryKeyHashFn', () => { - new QueryObserver(queryClient, { - queryKey: createKey(), - queryFn: () => Promise.resolve('data'), - // @ts-expect-error the callback must return a string - queryKeyHashFn: () => 42, - }) - - expectTypeOf< - Extract< - QueryObserverOptions['queryKeyHashFn'], - (...args: Array) => any - > - >().returns.toEqualTypeOf() - }) - }) - describe('structuralSharing', () => { it('should type a structuralSharing callback as unknown', () => { new QueryObserver(queryClient, { diff --git a/packages/query-core/src/__tests__/utils.test-d.tsx b/packages/query-core/src/__tests__/utils.test-d.tsx index fa2eb2d5227..55096aa768f 100644 --- a/packages/query-core/src/__tests__/utils.test-d.tsx +++ b/packages/query-core/src/__tests__/utils.test-d.tsx @@ -7,7 +7,7 @@ import { ensureQueryFn, functionalUpdate, hashKey, - hashQueryKeyByOptions, + hashKeyByOptions, isPlainArray, isPlainObject, isValidTimeout, @@ -29,6 +29,7 @@ import type { Mutation } from '../mutation' import type { Query } from '../query' import type { DataTag, + EqualityFn, MutationStatus, QueryFunction, QueryKey, @@ -507,18 +508,16 @@ describe('isPlainObject', () => { }) describe('partialMatchKey', () => { - it('should only expose the QueryKey overload, not the any implementation', () => { + it('should accept unknown values and an optional equality function', () => { + expectTypeOf(partialMatchKey).parameter(0).toEqualTypeOf() + expectTypeOf(partialMatchKey).parameter(1).toEqualTypeOf() expectTypeOf(partialMatchKey) - .parameter(0) - .toEqualTypeOf>() - expectTypeOf(partialMatchKey) - .parameter(1) - .toEqualTypeOf>() + .parameter(2) + .toEqualTypeOf() expectTypeOf(partialMatchKey).returns.toEqualTypeOf() expectTypeOf(partialMatchKey(['a'], ['a'])).toEqualTypeOf() - // @ts-expect-error a non-QueryKey argument is rejected - partialMatchKey(1, 2) + expectTypeOf(partialMatchKey(1, 2, Object.is)).toEqualTypeOf() }) }) @@ -538,11 +537,11 @@ describe('hashKey', () => { }) }) -describe('hashQueryKeyByOptions', () => { - it('should accept the options argument optionally', () => { - expectTypeOf(hashQueryKeyByOptions(['a'])).toEqualTypeOf() +describe('hashKeyByOptions', () => { + it('should accept a cache hash function', () => { + expectTypeOf(hashKeyByOptions(['a'], undefined)).toEqualTypeOf() expectTypeOf( - hashQueryKeyByOptions(['a'], { queryKeyHashFn: hashKey }), + hashKeyByOptions(['a'], { hashFn: hashKey }), ).toEqualTypeOf() }) }) @@ -643,9 +642,9 @@ describe('replaceEqualDeep', () => { .toEqualTypeOf() }) - it('should accept the depth argument optionally', () => { + it('should accept the equality function optionally', () => { expectTypeOf(replaceEqualDeep(1, 2)).toEqualTypeOf() - expectTypeOf(replaceEqualDeep(1, 2, 0)).toEqualTypeOf() + expectTypeOf(replaceEqualDeep(1, 2, Object.is)).toEqualTypeOf() }) }) diff --git a/packages/query-core/src/__tests__/utils.test.tsx b/packages/query-core/src/__tests__/utils.test.tsx index ee504a6f184..421bea2c671 100644 --- a/packages/query-core/src/__tests__/utils.test.tsx +++ b/packages/query-core/src/__tests__/utils.test.tsx @@ -8,7 +8,7 @@ import { addToStart, ensureQueryFn, hashKey, - hashQueryKeyByOptions, + hashKeyByOptions, isPlainArray, isPlainObject, isValidTimeout, @@ -23,13 +23,13 @@ import { import type { QueryFunctionContext } from '..' describe('core/utils', () => { - describe('hashQueryKeyByOptions', () => { + describe('hashKeyByOptions', () => { it('should use custom hash function when provided in options', () => { const key = ['test', { a: 1, b: 2 }] const customHashFn = vi.fn<() => string>(() => 'custom-hash') - const result = hashQueryKeyByOptions(key, { - queryKeyHashFn: customHashFn, + const result = hashKeyByOptions(key, { + hashFn: customHashFn, }) expect(customHashFn).toHaveBeenCalledWith(key) @@ -39,7 +39,7 @@ describe('core/utils', () => { it('should use default hash function when no options provided', () => { const key = ['test', { a: 1, b: 2 }] const defaultResult = hashKey(key) - const result = hashQueryKeyByOptions(key) + const result = hashKeyByOptions(key, undefined) expect(result).toStrictEqual(defaultResult) }) @@ -159,6 +159,38 @@ describe('core/utils', () => { }) describe('partialMatchKey', () => { + it('should use a custom equality function', () => { + const equalityFn = (a: unknown, b: unknown) => + typeof a === 'string' && typeof b === 'string' + ? a.toLowerCase() === b.toLowerCase() + : a === b + const a = ['todos', { status: 'done' }] + const b = ['TODOS', { status: 'DONE' }] + + expect(partialMatchKey(a, b)).toBe(false) + expect(partialMatchKey(a, b, equalityFn)).toBe(true) + }) + + it('should not structurally match different non-plain objects', () => { + const equalityFn = (a: unknown, b: unknown) => { + if (a instanceof Date && b instanceof Date) { + return a.toISOString() === b.toISOString() + } + return a === b + } + const a = ['report', { from: new Date('2021-06-25') }] + const b = ['report', { from: new Date('2020-01-01') }] + + expect(partialMatchKey(a, b, equalityFn)).toBe(false) + expect( + partialMatchKey( + a, + ['report', { from: new Date('2021-06-25') }], + equalityFn, + ), + ).toBe(true) + }) + it('should return `true` if a includes b', () => { const a = [{ a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] }] const b = [{ a: { b: 'b' }, c: 'c', d: [] }] @@ -242,6 +274,17 @@ describe('core/utils', () => { expect(replaceEqualDeep(date1, date2)).toBe(date2) }) + it('should use a custom equality function for value objects', () => { + const equalityFn = (a: unknown, b: unknown) => + a === b || + (a instanceof Date && b instanceof Date && a.getTime() === b.getTime()) + const prev = { date: new Date(0) } + const next = { date: new Date(0) } + + expect(replaceEqualDeep(prev, next)).not.toBe(prev) + expect(replaceEqualDeep(prev, next, equalityFn)).toBe(prev) + }) + it('should return the next value when the previous value is a different type', () => { const array = [1] const object = { a: 'a' } diff --git a/packages/query-core/src/index.ts b/packages/query-core/src/index.ts index c45e8e84f6b..7f65522129c 100644 --- a/packages/query-core/src/index.ts +++ b/packages/query-core/src/index.ts @@ -86,7 +86,9 @@ export type { InitialDataFunction, PlaceholderDataFunction, QueriesPlaceholderDataFunction, - QueryKeyHashFunction, + EqualityFn, + CacheKeyHashFunction, + CacheKeyConfig, GetPreviousPageParamFunction, GetNextPageParamFunction, InfiniteData, diff --git a/packages/query-core/src/mutationCache.ts b/packages/query-core/src/mutationCache.ts index 623169e1926..100c140b022 100644 --- a/packages/query-core/src/mutationCache.ts +++ b/packages/query-core/src/mutationCache.ts @@ -4,8 +4,10 @@ import { matchMutation, noop } from './utils' import type { Action, Mutation } from './mutation' import type { MutationObserver } from './mutationObserver' import type { + CacheKeyConfig, DefaultError, MutationFunctionContext, + MutationKey, NotifyEvent, } from './types' import type { MutationFilters } from './utils' @@ -21,6 +23,12 @@ import type { MutationFilters } from './utils' * If a callback returns a promise, it will be awaited before the mutation continues. */ export interface MutationCacheConfig { + /** + * Configures mutation key comparison and hashing globally. + * `equalityFn` compares individual values during partial matching and defaults to strict equality. + * `hashFn` hashes mutation keys for exact matching and mutation defaults. + */ + mutationKey?: CacheKeyConfig /** Called when any mutation in the cache encounters an error. */ onError?: ( error: DefaultError, @@ -298,7 +306,7 @@ export class MutationCache extends Subscribable { const defaultedFilters = { exact: true, ...filters } return this.getAll().find((mutation) => - matchMutation(defaultedFilters, mutation), + matchMutation(defaultedFilters, mutation, this.config.mutationKey), ) as Mutation | undefined } @@ -319,7 +327,9 @@ export class MutationCache extends Subscribable { * ``` */ findAll(filters: MutationFilters = {}): Array { - return this.getAll().filter((mutation) => matchMutation(filters, mutation)) + return this.getAll().filter((mutation) => + matchMutation(filters, mutation, this.config.mutationKey), + ) } /** diff --git a/packages/query-core/src/mutationObserver.ts b/packages/query-core/src/mutationObserver.ts index 2508d09e316..698416578bf 100644 --- a/packages/query-core/src/mutationObserver.ts +++ b/packages/query-core/src/mutationObserver.ts @@ -1,7 +1,7 @@ import { Mutation, getDefaultState } from './mutation' import { notifyManager } from './notifyManager' import { Subscribable } from './subscribable' -import { hashKey, shallowEqualObjects } from './utils' +import { hashKeyByOptions, shallowEqualObjects } from './utils' import type { Action } from './mutation' import type { QueryClient } from './queryClient' import type { @@ -120,7 +120,14 @@ export class MutationObserver< if ( prevOptions?.mutationKey && this.options.mutationKey && - hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey) + hashKeyByOptions( + prevOptions.mutationKey, + this.#client.getMutationCache().config.mutationKey, + ) !== + hashKeyByOptions( + this.options.mutationKey, + this.#client.getMutationCache().config.mutationKey, + ) ) { this.reset() } else if (this.#currentMutation?.state.status === 'pending') { diff --git a/packages/query-core/src/queryCache.ts b/packages/query-core/src/queryCache.ts index 1c748e2873d..00279784a57 100644 --- a/packages/query-core/src/queryCache.ts +++ b/packages/query-core/src/queryCache.ts @@ -1,11 +1,12 @@ import { notifyManager } from './notifyManager' import { Query } from './query' import { Subscribable } from './subscribable' -import { hashQueryKeyByOptions, matchQuery } from './utils' +import { hashKeyByOptions, matchQuery } from './utils' import type { Action, QueryState } from './query' import type { QueryClient } from './queryClient' import type { QueryObserver } from './queryObserver' import type { + CacheKeyConfig, DefaultError, NotifyEvent, QueryKey, @@ -23,6 +24,12 @@ import type { QueryFilters } from './utils' * are fire-and-forget: their return value is not awaited before the query settles. */ export interface QueryCacheConfig { + /** + * Configures query key comparison and hashing globally. + * `equalityFn` compares individual values during partial matching and defaults to strict equality. + * `hashFn` hashes query keys and defaults to `hashKey`. + */ + queryKey?: CacheKeyConfig /** Called when any query in the cache encounters an error. */ onError?: ( error: DefaultError, @@ -181,7 +188,7 @@ export class QueryCache extends Subscribable { ): Query { const queryKey = options.queryKey const queryHash = - options.queryHash ?? hashQueryKeyByOptions(queryKey, options) + options.queryHash ?? hashKeyByOptions(queryKey, this.config.queryKey) let query = this.get(queryHash) if (!query) { @@ -327,7 +334,7 @@ export class QueryCache extends Subscribable { const defaultedFilters = { exact: true, ...filters } return this.getAll().find((query) => - matchQuery(defaultedFilters, query), + matchQuery(defaultedFilters, query, this.config.queryKey), ) as Query | undefined } @@ -350,7 +357,9 @@ export class QueryCache extends Subscribable { findAll(filters: QueryFilters = {}): Array { const queries = this.getAll() return Object.keys(filters).length > 0 - ? queries.filter((query) => matchQuery(filters, query)) + ? queries.filter((query) => + matchQuery(filters, query, this.config.queryKey), + ) : queries } diff --git a/packages/query-core/src/queryClient.ts b/packages/query-core/src/queryClient.ts index 316aef6568b..4fcb2661fcb 100644 --- a/packages/query-core/src/queryClient.ts +++ b/packages/query-core/src/queryClient.ts @@ -5,8 +5,7 @@ import { onlineManager } from './onlineManager' import { QueryCache } from './queryCache' import { functionalUpdate, - hashKey, - hashQueryKeyByOptions, + hashKeyByOptions, noop, partialMatchKey, resolveQueryValue, @@ -761,10 +760,13 @@ export class QueryClient { > >, ): void { - this.#queryDefaults.set(hashKey(queryKey), { - queryKey, - defaultOptions: options, - }) + this.#queryDefaults.set( + hashKeyByOptions(queryKey, this.#queryCache.config.queryKey), + { + queryKey, + defaultOptions: options, + }, + ) } /** @@ -788,7 +790,13 @@ export class QueryClient { > = {} for (const queryDefault of this.#queryDefaults.values()) { - if (partialMatchKey(queryKey, queryDefault.queryKey)) { + if ( + partialMatchKey( + queryKey, + queryDefault.queryKey, + this.#queryCache.config.queryKey?.equalityFn, + ) + ) { Object.assign(result, queryDefault.defaultOptions) } } @@ -819,10 +827,13 @@ export class QueryClient { 'mutationKey' >, ): void { - this.#mutationDefaults.set(hashKey(mutationKey), { - mutationKey, - defaultOptions: options, - }) + this.#mutationDefaults.set( + hashKeyByOptions(mutationKey, this.#mutationCache.config.mutationKey), + { + mutationKey, + defaultOptions: options, + }, + ) } /** @@ -846,7 +857,13 @@ export class QueryClient { > = {} for (const queryDefault of this.#mutationDefaults.values()) { - if (partialMatchKey(mutationKey, queryDefault.mutationKey)) { + if ( + partialMatchKey( + mutationKey, + queryDefault.mutationKey, + this.#mutationCache.config.mutationKey?.equalityFn, + ) + ) { Object.assign(result, queryDefault.defaultOptions) } } @@ -912,9 +929,9 @@ export class QueryClient { } if (!defaultedOptions.queryHash) { - defaultedOptions.queryHash = hashQueryKeyByOptions( + defaultedOptions.queryHash = hashKeyByOptions( defaultedOptions.queryKey, - defaultedOptions, + this.#queryCache.config.queryKey, ) } diff --git a/packages/query-core/src/types.ts b/packages/query-core/src/types.ts index be9100f6049..30fd21df754 100644 --- a/packages/query-core/src/types.ts +++ b/packages/query-core/src/types.ts @@ -278,9 +278,27 @@ export type QueriesPlaceholderDataFunction = ( ) => TQueryData | undefined /** @inline */ -export type QueryKeyHashFunction = ( - queryKey: TQueryKey, -) => string +export type EqualityFn = (a: unknown, b: unknown) => boolean + +/** @inline */ +export type CacheKeyHashFunction< + TCacheKey extends ReadonlyArray = ReadonlyArray, +> = (cacheKey: TCacheKey) => string + +/** Configures the comparison and hashing of query or mutation keys for a cache. */ +export interface CacheKeyConfig< + TCacheKey extends ReadonlyArray = ReadonlyArray, +> { + /** + * Function used to compare values while partially matching keys. + * Defaults to strict equality. + */ + equalityFn?: EqualityFn + /** + * Function used to hash keys globally. + */ + hashFn?: CacheKeyHashFunction +} /** @inline */ export type GetPreviousPageParamFunction = ( @@ -399,8 +417,8 @@ export interface QueryOptions< */ persister?: QueryPersister, TPageParam> /** - * The hashed form of `queryKey`, computed with `queryKeyHashFn` (or the default hashing function otherwise). Used - * as the actual cache key internally. + * The cache key. If omitted, the query cache computes it from `queryKey` + * using its configured `hashFn` or the default hash function. */ queryHash?: string /** @@ -412,10 +430,6 @@ export interface QueryOptions< * The query will automatically update when this key changes (as long as `enabled` is not set to `false`). */ queryKey?: TQueryKey - /** - * If specified, this function is used to hash the `queryKey` to a string. - */ - queryKeyHashFn?: QueryKeyHashFunction /** * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been * created or cached yet). diff --git a/packages/query-core/src/utils.ts b/packages/query-core/src/utils.ts index ead7382c4cd..2176a5ef99d 100644 --- a/packages/query-core/src/utils.ts +++ b/packages/query-core/src/utils.ts @@ -2,7 +2,9 @@ import { timeoutManager } from './timeoutManager' import type { Mutation } from './mutation' import type { FetchOptions, Query } from './query' import type { + CacheKeyConfig, DefaultError, + EqualityFn, FetchStatus, MutationKey, MutationStatus, @@ -187,6 +189,7 @@ export function resolveQueryValue< * Every filter that is specified must match; filters that are left unspecified are ignored. * @param filters - The filters to check the query against. * @param query - The query to check. + * @param keyConfig - The cache configuration for key comparison and hashing. * @returns `true` if the query matches every specified filter. * @example * ```ts @@ -200,6 +203,7 @@ export function resolveQueryValue< export function matchQuery( filters: QueryFilters, query: Query, + keyConfig?: CacheKeyConfig, ): boolean { const { type = 'all', @@ -212,10 +216,12 @@ export function matchQuery( if (queryKey) { if (exact) { - if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) { + if (query.queryHash !== hashKeyByOptions(queryKey, keyConfig)) { return false } - } else if (!partialMatchKey(query.queryKey, queryKey)) { + } else if ( + !partialMatchKey(query.queryKey, queryKey, keyConfig?.equalityFn) + ) { return false } } @@ -251,6 +257,7 @@ export function matchQuery( * If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match. * @param filters - The filters to check the mutation against. * @param mutation - The mutation to check. + * @param keyConfig - The cache configuration for key comparison and hashing. * @returns `true` if the mutation matches every specified filter. * @example * ```ts @@ -264,6 +271,7 @@ export function matchQuery( export function matchMutation( filters: MutationFilters, mutation: Mutation, + keyConfig?: CacheKeyConfig, ): boolean { const { exact, status, predicate, mutationKey } = filters if (mutationKey) { @@ -271,10 +279,19 @@ export function matchMutation( return false } if (exact) { - if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) { + if ( + hashKeyByOptions(mutation.options.mutationKey, keyConfig) !== + hashKeyByOptions(mutationKey, keyConfig) + ) { return false } - } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) { + } else if ( + !partialMatchKey( + mutation.options.mutationKey, + mutationKey, + keyConfig?.equalityFn, + ) + ) { return false } } @@ -291,17 +308,19 @@ export function matchMutation( } /** - * Hashes a query key with the query's `queryKeyHashFn` option, falling back to {@link hashKey}. - * @param queryKey - The query key to hash. - * @param options - The query options that may provide a custom `queryKeyHashFn`. - * @returns The query hash, a string that identifies the query in the cache. + * Hashes a cache key with the cache's `hashFn`, falling back to {@link hashKey}. + * @param cacheKey - The query or mutation key to hash. + * @param keyConfig - The cache configuration that may provide a custom `hashFn`. + * @returns The hash, a string that identifies the key in the cache. */ -export function hashQueryKeyByOptions( - queryKey: TQueryKey, - options?: Pick, 'queryKeyHashFn'>, +export function hashKeyByOptions< + TCacheKey extends ReadonlyArray = ReadonlyArray, +>( + cacheKey: TCacheKey, + keyConfig: CacheKeyConfig | undefined, ): string { - const hashFn = options?.queryKeyHashFn || hashKey - return hashFn(queryKey) + const hashFn = keyConfig?.hashFn ?? hashKey + return hashFn(cacheKey) } /** @@ -328,16 +347,32 @@ export function hashKey(queryKey: QueryKey | MutationKey): string { ) } +const defaultEqualityFn: EqualityFn = (a, b) => a === b + /** * Checks if key `b` partially matches with key `a`. * @param a - The key to check, e.g. a query's own key. * @param b - The (partial) key to match against `a`. + * @param equalityFn - Compares individual key values. Defaults to strict equality. * @returns `true` if every array element or object property in `b` matches the one at the same * position in `a`. */ -export function partialMatchKey(a: QueryKey, b: QueryKey): boolean -export function partialMatchKey(a: any, b: any): boolean { - if (a === b) { +export function partialMatchKey( + a: QueryKey, + b: QueryKey, + equalityFn?: EqualityFn, +): boolean +export function partialMatchKey( + a: unknown, + b: unknown, + equalityFn?: EqualityFn, +): boolean +export function partialMatchKey( + a: any, + b: any, + equalityFn: EqualityFn = defaultEqualityFn, +): boolean { + if (equalityFn(a, b)) { return true } @@ -345,20 +380,20 @@ export function partialMatchKey(a: any, b: any): boolean { return false } - if (a && b && typeof a === 'object' && typeof b === 'object') { - if (Array.isArray(a) && Array.isArray(b)) { - if (b.length > a.length) return false - for (let i = 0; i < b.length; i++) { - if (!partialMatchKey(a[i], b[i])) { - return false - } + if (isPlainArray(a) && isPlainArray(b)) { + if (b.length > a.length) return false + for (let i = 0; i < b.length; i++) { + if (!partialMatchKey(a[i], b[i], equalityFn)) { + return false } - return true } + return true + } + if (isPlainObject(a) && isPlainObject(b)) { const bKeys = Object.keys(b) for (const key of bKeys) { - if (!partialMatchKey(a[key], b[key])) { + if (!partialMatchKey(a[key], b[key], equalityFn)) { return false } } @@ -374,15 +409,41 @@ const hasOwn = Object.prototype.hasOwnProperty * This function returns `a` if `b` is deeply equal. * If not, it will replace any deeply equal children of `b` with those of `a`. * This can be used for structural sharing between JSON values for example. + * An optional equality function can be used for custom value types. * @param a - The previous value, whose deeply equal parts are reused. * @param b - The new value. - * @param depth - The current recursion depth. Past a depth of `500`, `b` is returned as is. + * @param equalityFn - Compares values for structural sharing. Defaults to strict equality. * @returns `a` if `b` is deeply equal to it, otherwise `b` with its deeply equal parts replaced by * those of `a`. */ -export function replaceEqualDeep(a: unknown, b: T, depth?: number): T -export function replaceEqualDeep(a: any, b: any, depth = 0): any { - if (a === b) { +export function replaceEqualDeep( + a: unknown, + b: T, + equalityFn?: EqualityFn, +): T +export function replaceEqualDeep( + a: any, + b: any, + equalityFn: EqualityFn = defaultEqualityFn, +): any { + return replaceEqualDeepInternal(a, b, equalityFn, 0) +} + +/** + * Reuses deeply equal values while limiting recursion to 500 levels. + * @param a - The previous value. + * @param b - The new value. + * @param equalityFn - Compares values for structural sharing. + * @param depth - The current recursion depth. + * @returns The new value with deeply equal parts of the previous value reused. + */ +function replaceEqualDeepInternal( + a: any, + b: any, + equalityFn: EqualityFn, + depth: number, +): any { + if (equalityFn(a, b)) { return a } @@ -405,7 +466,7 @@ export function replaceEqualDeep(a: any, b: any, depth = 0): any { const aItem = a[key] const bItem = b[key] - if (aItem === bItem) { + if (equalityFn(aItem, bItem)) { copy[key] = aItem if (array ? i < aSize : hasOwn.call(a, key)) equalItems++ continue @@ -421,7 +482,7 @@ export function replaceEqualDeep(a: any, b: any, depth = 0): any { continue } - const v = replaceEqualDeep(aItem, bItem, depth + 1) + const v = replaceEqualDeepInternal(aItem, bItem, equalityFn, depth + 1) copy[key] = v if (v === aItem) equalItems++ } diff --git a/packages/query-devtools/src/__tests__/Devtools.test.tsx b/packages/query-devtools/src/__tests__/Devtools.test.tsx index 9e2577a2573..77836428d27 100644 --- a/packages/query-devtools/src/__tests__/Devtools.test.tsx +++ b/packages/query-devtools/src/__tests__/Devtools.test.tsx @@ -2,6 +2,7 @@ import { createLocalStorage } from '@solid-primitives/storage' import { cleanup, fireEvent, render, within } from '@solidjs/testing-library' import { Mutation, + QueryCache, QueryClient, QueryObserver, dehydrate, @@ -921,10 +922,14 @@ describe('Devtools', () => { }) it('should render a query row when a hydrated query uses a custom hash function', async () => { + queryClient = new QueryClient({ + queryCache: new QueryCache({ + queryKey: { hashFn: () => 'custom-posts-hash' }, + }), + }) queryClient.query({ queryKey: ['posts'], queryFn: () => [{ id: 1 }], - queryKeyHashFn: () => 'custom-posts-hash', }) await vi.advanceTimersByTimeAsync(0) const dehydratedState = dehydrate(queryClient) diff --git a/packages/react-query/src/__tests__/useQuery.test.tsx b/packages/react-query/src/__tests__/useQuery.test.tsx index ae909852f34..5d5063c2958 100644 --- a/packages/react-query/src/__tests__/useQuery.test.tsx +++ b/packages/react-query/src/__tests__/useQuery.test.tsx @@ -4980,17 +4980,21 @@ describe('useQuery', () => { let hashes = 0 let renders = 0 - function queryKeyHashFn(x: any) { + function hashFn(queryKey: ReadonlyArray) { hashes++ - return JSON.stringify(x) + return JSON.stringify(queryKey) } + queryClient = new QueryClient({ + queryCache: new QueryCache({ queryKey: { hashFn } }), + }) + function Page() { React.useEffect(() => { renders++ }) - useQuery({ queryKey: key, queryFn: () => 'test', queryKeyHashFn }) + useQuery({ queryKey: key, queryFn: () => 'test' }) return null } @@ -5003,15 +5007,19 @@ describe('useQuery', () => { it('should hash query keys that contain bigints given a supported query hash function', async () => { const key = [createKey(), 1n] - function queryKeyHashFn(x: any) { - return JSON.stringify(x, (_, value) => { + function hashFn(queryKey: ReadonlyArray) { + return JSON.stringify(queryKey, (_, value) => { if (typeof value === 'bigint') return value.toString() return value }) } + queryClient = new QueryClient({ + queryCache: new QueryCache({ queryKey: { hashFn } }), + }) + function Page() { - useQuery({ queryKey: key, queryFn: () => 'test', queryKeyHashFn }) + useQuery({ queryKey: key, queryFn: () => 'test' }) return null } @@ -5019,7 +5027,7 @@ describe('useQuery', () => { await vi.advanceTimersByTimeAsync(0) - const query = queryClient.getQueryCache().get(queryKeyHashFn(key)) + const query = queryClient.getQueryCache().get(hashFn(key)) expect(query?.state.data).toBe('test') }) diff --git a/packages/solid-query/src/__tests__/useQuery.test.tsx b/packages/solid-query/src/__tests__/useQuery.test.tsx index 9dd6902b192..bac3eed6296 100644 --- a/packages/solid-query/src/__tests__/useQuery.test.tsx +++ b/packages/solid-query/src/__tests__/useQuery.test.tsx @@ -4403,16 +4403,19 @@ describe('useQuery', () => { let hashes = 0 - function queryKeyHashFn(x: any) { + function hashFn(queryKey: ReadonlyArray) { hashes++ - return JSON.stringify(x) + return JSON.stringify(queryKey) } + queryClient = new QueryClient({ + queryCache: new QueryCache({ queryKey: { hashFn } }), + }) + function Page() { useQuery(() => ({ queryKey: key, queryFn: () => sleep(10).then(() => 'test'), - queryKeyHashFn, })) return null