Skip to content

Commit

Permalink
fix(query-core): notify queryCache after updateQuery() (#6936)
Browse files Browse the repository at this point in the history
so that it's never undefined
  • Loading branch information
TkDodo committed Feb 19, 2024
1 parent 26d8980 commit 35fa47d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
16 changes: 8 additions & 8 deletions packages/query-core/src/queryObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,14 +146,6 @@ export class QueryObserver<

this.options = this.#client.defaultQueryOptions(options)

if (!shallowEqualObjects(this.options, prevOptions)) {
this.#client.getQueryCache().notify({
type: 'observerOptionsUpdated',
query: this.#currentQuery,
observer: this,
})
}

if (
typeof this.options.enabled !== 'undefined' &&
typeof this.options.enabled !== 'boolean'
Expand All @@ -163,6 +155,14 @@ export class QueryObserver<

this.#updateQuery()

if (!shallowEqualObjects(this.options, prevOptions)) {
this.#client.getQueryCache().notify({
type: 'observerOptionsUpdated',
query: this.#currentQuery,
observer: this,
})
}

const mounted = this.hasListeners()

// Fetch if there are subscribers
Expand Down
8 changes: 7 additions & 1 deletion packages/query-core/src/tests/queryCache.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,10 @@ describe('queryCache', () => {
test('should notify query cache when a query becomes stale', async () => {
const key = queryKey()
const events: Array<string> = []
const queries: Array<unknown> = []
const unsubscribe = queryCache.subscribe((event) => {
events.push(event.type)
queries.push(event.query)
})

const observer = new QueryObserver(queryClient, {
Expand All @@ -57,8 +59,8 @@ describe('queryCache', () => {
})

expect(events).toEqual([
'observerOptionsUpdated',
'added', // 1. Query added -> loading
'observerOptionsUpdated',
'observerResultsUpdated', // 2. Observer result updated -> loading
'observerAdded', // 3. Observer added
'observerResultsUpdated', // 4. Observer result updated -> fetching
Expand All @@ -68,6 +70,10 @@ describe('queryCache', () => {
'observerResultsUpdated', // 8. Observer result updated -> stale
])

queries.forEach((query) => {
expect(query).toBeDefined()
})

unsubscribe()
unsubScribeObserver()
})
Expand Down

0 comments on commit 35fa47d

Please sign in to comment.