Skip to content

Commit 3ff6ee7

Browse files
feat (QueryClient): new fn getQueriesData for matching multiple queries
Similar to setQueriesData, a "get" version to fuzzily return multiple matching queries.
1 parent 60eb974 commit 3ff6ee7

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/core/queryClient.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,21 @@ export class QueryClient {
111111
return this.queryCache.find<TData>(queryKey, filters)?.state.data
112112
}
113113

114+
getQueriesData<TData = unknown>(queryKey: QueryKey): [QueryKey, TData][]
115+
getQueriesData<TData = unknown>(filters: QueryFilters): [QueryKey, TData][]
116+
getQueriesData<TData = unknown>(
117+
queryKeyOrFilters: QueryKey | QueryFilters
118+
): [QueryKey, TData][] {
119+
return notifyManager.batch(() =>
120+
this.getQueryCache()
121+
.findAll(queryKeyOrFilters)
122+
.map(({ queryKey, state }) => {
123+
const data = state.data as TData
124+
return [queryKey, data]
125+
})
126+
)
127+
}
128+
114129
setQueryData<TData>(
115130
queryKey: QueryKey,
116131
updater: Updater<TData | undefined, TData>,

src/core/tests/queryClient.test.tsx

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,37 @@ describe('queryClient', () => {
223223
})
224224
})
225225

226+
describe('getQueriesData', () => {
227+
test('should return the query data for all matched queries', () => {
228+
const key1 = queryKey()
229+
const key2 = queryKey()
230+
queryClient.setQueryData([key1, 1], 1)
231+
queryClient.setQueryData([key1, 2], 2)
232+
queryClient.setQueryData([key2, 2], 2)
233+
expect(queryClient.getQueriesData([key1])).toEqual([
234+
[[key1, 1], 1],
235+
[[key1, 2], 2],
236+
])
237+
})
238+
239+
test('should return empty array if queries are not found', () => {
240+
const key = queryKey()
241+
expect(queryClient.getQueriesData(key)).toEqual([])
242+
})
243+
244+
test('should accept query filters', () => {
245+
queryClient.setQueryData(['key', 1], 1)
246+
queryClient.setQueryData(['key', 2], 2)
247+
const query1 = queryCache.find(['key', 1])!
248+
249+
const result = queryClient.getQueriesData({
250+
predicate: query => query === query1,
251+
})
252+
253+
expect(result).toEqual([[['key', 1], 1]])
254+
})
255+
})
256+
226257
describe('fetchQuery', () => {
227258
test('should not type-error with strict query key', async () => {
228259
type StrictData = 'data'

0 commit comments

Comments
 (0)