Skip to content
Merged
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/stable-observers-notify.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@tanstack/query-core': patch
---

Notify every query observer when another observer unsubscribes synchronously during the same query update.
21 changes: 21 additions & 0 deletions packages/query-core/src/__tests__/query.test.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -824,6 +824,27 @@ describe('query', () => {
notifySpy.mockRestore()
})

it('should notify remaining observers when one unsubscribes during an update', () => {
const key = queryKey()
const options = { queryKey: key, enabled: false }
const firstObserver = new QueryObserver(queryClient, options)
const secondObserver = new QueryObserver(queryClient, options)
const secondListener = vi.fn()

let unsubscribeFirst: () => void = () => undefined
unsubscribeFirst = firstObserver.subscribe(() => {
unsubscribeFirst()
})
const unsubscribeSecond = secondObserver.subscribe(secondListener)

queryClient.setQueryData(key, 'data')

expect(secondListener).toHaveBeenCalledTimes(1)
expect(secondObserver.getCurrentResult().data).toBe('data')

unsubscribeSecond()
})

it('should not change state on invalidate() if already invalidated', async () => {
const key = queryKey()

Expand Down
4 changes: 3 additions & 1 deletion packages/query-core/src/query.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -704,7 +704,9 @@ export class Query<
this.state = reducer(this.state)

notifyManager.batch(() => {
this.observers.forEach((observer) => {
// Keep the current iteration stable if an observer unsubscribes
// synchronously while it is being notified.
this.observers.slice().forEach((observer) => {
observer.onQueryUpdate()
})

Expand Down
Loading