diff --git a/.changeset/coalesce-devtools-query-cache-events.md b/.changeset/coalesce-devtools-query-cache-events.md new file mode 100644 index 00000000000..4b7593972f2 --- /dev/null +++ b/.changeset/coalesce-devtools-query-cache-events.md @@ -0,0 +1,5 @@ +--- +'@tanstack/query-devtools': patch +--- + +fix(query-devtools): coalesce query cache events per microtask to update the list once on 'clear' and 'removeQueries' diff --git a/packages/query-devtools/src/Devtools.tsx b/packages/query-devtools/src/Devtools.tsx index a55dd7c6339..649710dd12c 100644 --- a/packages/query-devtools/src/Devtools.tsx +++ b/packages/query-devtools/src/Devtools.tsx @@ -1058,7 +1058,7 @@ export const ContentView: Component = (props) => { onClick={() => { if (selectedView() === 'queries') { sendDevToolsEvent({ type: 'CLEAR_QUERY_CACHE' }) - batch(() => query_cache().clear()) + query_cache().clear() } else { sendDevToolsEvent({ type: 'CLEAR_MUTATION_CACHE' }) mutation_cache().clear() @@ -2215,12 +2215,27 @@ const setupQueryCacheSubscription = () => { createEffect(() => { const cache = queryCache() - const unsubscribe = cache.subscribe((event) => { + let active = true + const pendingUpdates = new Map void>() + const flush = () => { + if (!active) return + const updates = [...pendingUpdates.values()] + pendingUpdates.clear() batch(() => { - queryCacheSubscriptions.notify(() => cache, event) + updates.forEach((update) => update()) }) + } + const schedule = (update: () => void, id: symbol) => { + if (!pendingUpdates.size) queueMicrotask(flush) + pendingUpdates.set(id, update) + } + const unsubscribe = cache.subscribe((event) => { + queryCacheSubscriptions.notify(() => cache, event, schedule) + }) + onCleanup(() => { + active = false + unsubscribe() }) - onCleanup(unsubscribe) }) } diff --git a/packages/query-devtools/src/__tests__/Devtools.test.tsx b/packages/query-devtools/src/__tests__/Devtools.test.tsx index 46a94087b8e..9d88afd4678 100644 --- a/packages/query-devtools/src/__tests__/Devtools.test.tsx +++ b/packages/query-devtools/src/__tests__/Devtools.test.tsx @@ -184,7 +184,7 @@ describe('Devtools', () => { } } - it('keeps selected query details updating when its row is offscreen', () => { + it('keeps selected query details updating when its row is offscreen', async () => { seedQueries() const rendered = renderDevtools( { initialIsOpen: true }, @@ -199,13 +199,14 @@ describe('Devtools', () => { expect(rendered.getByLabelText('Query key ["query-0999"]')).toBeVisible() queryClient.setQueryData(['query-0000'], 'updated-selected-data') + await vi.advanceTimersByTimeAsync(0) expect(rendered.getByDisplayValue('updated-selected-data')).toBeVisible() viewport.scrollTo({ top: 0 }) expect(rendered.getByLabelText('Query key ["query-0000"]')).toBeVisible() expect(rendered.getByText('Query Details')).toBeVisible() }) - it('filters, clears, and restores queries after distant scrolling', () => { + it('filters, clears, and restores queries after distant scrolling', async () => { seedQueries() const rendered = renderDevtools({ initialIsOpen: true }) const viewport = getViewport(rendered.container, 'queries') @@ -222,13 +223,15 @@ describe('Devtools', () => { expect(rendered.getAllByLabelText(/^Query key /).length).toBeLessThan(100) viewport.scrollTo({ top: viewport.scrollHeight }) fireEvent.click(rendered.getByLabelText('Clear query cache')) + await vi.advanceTimersByTimeAsync(0) expect(rendered.queryAllByLabelText(/^Query key /)).toHaveLength(0) queryClient.setQueryData(['after-clear'], 'restored') + await vi.advanceTimersByTimeAsync(0) viewport.scrollTo({ top: viewport.scrollTop }) expect(rendered.getByLabelText('Query key ["after-clear"]')).toBeVisible() }) - it('should update the query list once when clearing the query cache', () => { + it('should update the query list once when clearing the query cache', async () => { seedQueries() const rendered = renderDevtools({ initialIsOpen: true }) const content = getViewport( @@ -236,17 +239,75 @@ describe('Devtools', () => { 'queries', ).firstElementChild assert(content) - const observer = new MutationObserver(noop) + const records: Array = [] + const observer = new MutationObserver((mutations) => { + records.push(...mutations) + }) observer.observe(content, { attributeFilter: ['style'] }) fireEvent.click(rendered.getByLabelText('Clear query cache')) + await vi.advanceTimersByTimeAsync(0) + + records.push(...observer.takeRecords()) + observer.disconnect() + expect(records).toHaveLength(1) + expect(rendered.queryAllByLabelText(/^Query key /)).toHaveLength(0) + }) + + it('should update the query list once when the query client clears the cache', async () => { + seedQueries() + const rendered = renderDevtools({ initialIsOpen: true }) + const content = getViewport( + rendered.container, + 'queries', + ).firstElementChild + assert(content) + const records: Array = [] + const observer = new MutationObserver((mutations) => { + records.push(...mutations) + }) + observer.observe(content, { attributeFilter: ['style'] }) + + queryClient.clear() + await vi.advanceTimersByTimeAsync(0) - const records = observer.takeRecords() + records.push(...observer.takeRecords()) observer.disconnect() expect(records).toHaveLength(1) expect(rendered.queryAllByLabelText(/^Query key /)).toHaveLength(0) }) + it('should update the query list once when the query client removes queries', async () => { + seedQueries() + const rendered = renderDevtools( + { initialIsOpen: true }, + { 'TanstackQueryDevtools.sort': 'query hash' }, + ) + const content = getViewport( + rendered.container, + 'queries', + ).firstElementChild + assert(content) + const records: Array = [] + const observer = new MutationObserver((mutations) => { + records.push(...mutations) + }) + observer.observe(content, { attributeFilter: ['style'] }) + + queryClient.removeQueries({ + predicate: (query) => String(query.queryKey[0]) < 'query-0500', + }) + await vi.advanceTimersByTimeAsync(0) + + records.push(...observer.takeRecords()) + observer.disconnect() + expect(records).toHaveLength(1) + expect( + rendered.queryByLabelText('Query key ["query-0499"]'), + ).not.toBeInTheDocument() + expect(rendered.getByLabelText('Query key ["query-0500"]')).toBeVisible() + }) + it('keeps query clicks aligned after a same-count sort change', () => { seedQueries() const rendered = renderDevtools( @@ -399,7 +460,7 @@ describe('Devtools', () => { )) } - it('should keep cache notifications and cleanup independent for the same query key', () => { + it('should keep cache notifications and cleanup independent for the same query key', async () => { const secondClient = new QueryClient() queryClient.setQueryData(['shared-key'], 'first-data') secondClient.setQueryData(['shared-key'], 'second-data') @@ -411,6 +472,7 @@ describe('Devtools', () => { fireEvent.click(second.getByLabelText('Query key ["shared-key"]')) secondClient.setQueryData(['shared-key'], 'updated-second') + await vi.advanceTimersByTimeAsync(0) expect(first.getByDisplayValue('first-data')).toBeInTheDocument() expect( first.queryByDisplayValue('updated-second'), @@ -419,6 +481,7 @@ describe('Devtools', () => { secondRender.unmount() queryClient.setQueryData(['shared-key'], 'updated-first') + await vi.advanceTimersByTimeAsync(0) expect(first.getByDisplayValue('updated-first')).toBeInTheDocument() secondClient.clear() }) @@ -507,7 +570,7 @@ describe('Devtools', () => { ) }) - it('should switch cache subscriptions when the client changes', () => { + it('should switch cache subscriptions when the client changes', async () => { const secondClient = new QueryClient() queryClient.setQueryData(['switch-key'], 'old-client') secondClient.setQueryData(['switch-key'], 'new-client') @@ -529,8 +592,10 @@ describe('Devtools', () => { setClient(secondClient) expect(panel.getByDisplayValue('new-client')).toBeInTheDocument() secondClient.setQueryData(['switch-key'], 'new-update') + await vi.advanceTimersByTimeAsync(0) expect(panel.getByDisplayValue('new-update')).toBeInTheDocument() queryClient.setQueryData(['switch-key'], 'old-update') + await vi.advanceTimersByTimeAsync(0) expect(panel.getByDisplayValue('new-update')).toBeInTheDocument() rendered.unmount() secondClient.clear() @@ -748,7 +813,7 @@ describe('Devtools', () => { ).toBeInTheDocument() }) - it('should reflect a newly added query reactively', () => { + it('should reflect a newly added query reactively', async () => { const rendered = renderDevtools({ initialIsOpen: true }) expect( @@ -756,6 +821,7 @@ describe('Devtools', () => { ).not.toBeInTheDocument() queryClient.setQueryData(['new'], 'hello') + await vi.advanceTimersByTimeAsync(0) expect(rendered.getByLabelText(/Query key \["new"\]/)).toBeInTheDocument() }) @@ -915,12 +981,13 @@ describe('Devtools', () => { ]) }) - it('should clear all queries when the clear cache button is clicked', () => { + it('should clear all queries when the clear cache button is clicked', async () => { queryClient.setQueryData(['posts'], []) queryClient.setQueryData(['users'], []) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText('Clear query cache')) + await vi.advanceTimersByTimeAsync(0) expect( rendered.queryByLabelText(/Query key \["posts"\]/), ).not.toBeInTheDocument() @@ -1200,12 +1267,13 @@ describe('Devtools', () => { expect(rendered.getByLabelText(/Inactive: \d+/)).toBeInTheDocument() }) - it('should reflect the inactive count when a query is added without observers', () => { + it('should reflect the inactive count when a query is added without observers', async () => { const rendered = renderDevtools({ initialIsOpen: true }) expect(rendered.getByLabelText('Inactive: 0')).toBeInTheDocument() queryClient.setQueryData(['posts'], [{ id: 1 }]) + await vi.advanceTimersByTimeAsync(0) expect(rendered.getByLabelText('Inactive: 1')).toBeInTheDocument() }) @@ -1289,7 +1357,7 @@ describe('Devtools', () => { }) describe('Data Explorer search', () => { - it('searches only query Data and resets search when the selection changes', () => { + it('searches only query Data and resets search when the selection changes', async () => { queryClient.setQueryData(['search-first'], { nested: { name: 'first needle' }, }) @@ -1315,6 +1383,7 @@ describe('Devtools', () => { queryClient.setQueryData(['search-first'], { nested: { name: 'updated needle' }, }) + await vi.advanceTimersByTimeAsync(0) expect(data.getByLabelText('name:')).toHaveValue('updated needle') fireEvent.click(rendered.getByLabelText('Query key ["search-second"]')) expect(rendered.getByLabelText('Search data')).toHaveValue('') @@ -1464,12 +1533,13 @@ describe('Devtools', () => { }) describe('query actions', () => { - it('should remove the query when the "Remove" button is clicked', () => { + it('should remove the query when the "Remove" button is clicked', async () => { queryClient.setQueryData(['action-remove'], [{ id: 1 }]) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText(/Query key \["action-remove"\]/)) fireEvent.click(rendered.getByText('Remove')) + await vi.advanceTimersByTimeAsync(0) expect( rendered.queryByLabelText(/Query key \["action-remove"\]/), ).not.toBeInTheDocument() @@ -1528,7 +1598,7 @@ describe('Devtools', () => { expect(queryClient.getQueryState(['action-error'])?.status).toBe('error') }) - it('should restore the query status when "Restore Error" is clicked after "Trigger Error"', () => { + it('should restore the query status when "Restore Error" is clicked after "Trigger Error"', async () => { queryClient.setQueryData(['action-restore-error'], [{ id: 1 }]) const rendered = renderDevtools({ initialIsOpen: true }) @@ -1536,6 +1606,7 @@ describe('Devtools', () => { rendered.getByLabelText(/Query key \["action-restore-error"\]/), ) fireEvent.click(rendered.getByText('Trigger Error')) + await vi.advanceTimersByTimeAsync(0) fireEvent.click(rendered.getByText('Restore Error')) expect(queryClient.getQueryState(['action-restore-error'])?.status).toBe( 'pending', @@ -1564,6 +1635,7 @@ describe('Devtools', () => { // First click puts the query into a pending state with `data: undefined` // and stashes the original options in `fetchMeta.__previousQueryOptions`. fireEvent.click(rendered.getByText('Trigger Loading')) + await vi.advanceTimersByTimeAsync(0) expect( queryClient.getQueryState(['action-restore-loading'])?.status, ).toBe('pending') diff --git a/packages/query-devtools/src/__tests__/createCacheSubscriptionRegistry.test.ts b/packages/query-devtools/src/__tests__/createCacheSubscriptionRegistry.test.ts index 9a8912b8a62..7685654f268 100644 --- a/packages/query-devtools/src/__tests__/createCacheSubscriptionRegistry.test.ts +++ b/packages/query-devtools/src/__tests__/createCacheSubscriptionRegistry.test.ts @@ -37,4 +37,37 @@ describe('createCacheSubscriptionRegistry', () => { secondDispose() } }) + + it('should pass the same id to schedule for repeated updates of one subscription', () => { + const registry = createCacheSubscriptionRegistry() + const pending = new Map void>() + const [firstValue, setFirstValue] = createSignal(0) + const [secondValue, setSecondValue] = createSignal(0) + const dispose = createRoot((disposeRoot) => { + registry.register((cache) => cache(), setFirstValue) + registry.register((cache) => cache() * 10, setSecondValue) + return disposeRoot + }) + + try { + registry.notify( + () => 1, + undefined, + (update, id) => pending.set(id, update), + ) + registry.notify( + () => 2, + undefined, + (update, id) => pending.set(id, update), + ) + expect(pending.size).toBe(2) + + pending.forEach((update) => update()) + + expect(firstValue()).toBe(2) + expect(secondValue()).toBe(20) + } finally { + dispose() + } + }) }) diff --git a/packages/query-devtools/src/createCacheSubscriptionRegistry.ts b/packages/query-devtools/src/createCacheSubscriptionRegistry.ts index cf6c658f080..469ab69151a 100644 --- a/packages/query-devtools/src/createCacheSubscriptionRegistry.ts +++ b/packages/query-devtools/src/createCacheSubscriptionRegistry.ts @@ -42,18 +42,19 @@ export function createCacheSubscriptionRegistry() { * Updates every subscription whose `shouldUpdate` accepts the event. * @param cache - The cache to compute the values from. * @param event - The cache event. - * @param schedule - Runs each update. Defaults to running it right away. + * @param schedule - Runs each update, receiving the subscription's id so repeated updates of the + * same subscription can be merged. Defaults to running it right away. */ function notify( cache: Accessor, event: TEvent, - schedule: (update: () => void) => void = (update) => update(), + schedule: (update: () => void, id: symbol) => void = (update) => update(), ) { for (const [id, subscription] of subscriptions) { if (!subscription.shouldUpdate(event)) continue schedule(() => { if (subscriptions.has(id)) subscription.update(cache) - }) + }, id) } }