Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/coalesce-devtools-query-cache-events.md
Original file line number Diff line number Diff line change
@@ -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'
23 changes: 19 additions & 4 deletions packages/query-devtools/src/Devtools.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1058,7 +1058,7 @@ export const ContentView: Component<ContentViewProps> = (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()
Expand Down Expand Up @@ -2215,12 +2215,27 @@ const setupQueryCacheSubscription = () => {

createEffect(() => {
const cache = queryCache()
const unsubscribe = cache.subscribe((event) => {
let active = true
const pendingUpdates = new Map<symbol, () => 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)
})
}

Expand Down
98 changes: 85 additions & 13 deletions packages/query-devtools/src/__tests__/Devtools.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand All @@ -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')
Expand All @@ -222,31 +223,91 @@ 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(
rendered.container,
'queries',
).firstElementChild
assert(content)
const observer = new MutationObserver(noop)
const records: Array<MutationRecord> = []
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<MutationRecord> = []
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<MutationRecord> = []
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(
Expand Down Expand Up @@ -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')
Expand All @@ -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'),
Expand All @@ -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()
})
Expand Down Expand Up @@ -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')
Expand All @@ -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()
Expand Down Expand Up @@ -748,14 +813,15 @@ 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(
rendered.queryByLabelText(/Query key \["new"\]/),
).not.toBeInTheDocument()

queryClient.setQueryData(['new'], 'hello')
await vi.advanceTimersByTimeAsync(0)

expect(rendered.getByLabelText(/Query key \["new"\]/)).toBeInTheDocument()
})
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()
})
Expand Down Expand Up @@ -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' },
})
Expand All @@ -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('')
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -1528,14 +1598,15 @@ 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 })

fireEvent.click(
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',
Expand Down Expand Up @@ -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')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,37 @@ describe('createCacheSubscriptionRegistry', () => {
secondDispose()
}
})

it('should pass the same id to schedule for repeated updates of one subscription', () => {
const registry = createCacheSubscriptionRegistry<number, undefined>()
const pending = new Map<symbol, () => 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()
}
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -42,18 +42,19 @@ export function createCacheSubscriptionRegistry<TCache, TEvent>() {
* 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<TCache>,
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)
}
}

Expand Down
Loading