Skip to content

Commit

Permalink
feat: warn when there are multiple observers mounted at the same time…
Browse files Browse the repository at this point in the history
… with different staleTimes
  • Loading branch information
TkDodo committed Nov 20, 2024
1 parent 0c4040e commit 3ae6bff
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
56 changes: 56 additions & 0 deletions packages/query-core/src/__tests__/query.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1045,4 +1045,60 @@ describe('query', () => {

expect(query.state.status).toBe('error')
})

it('should warn when multiple observers have different staleTimes when mounted at the same time', async () => {
const consoleMock = vi.spyOn(console, 'error')
consoleMock.mockImplementation(() => undefined)
const key = queryKey()
const observer1 = new QueryObserver(queryClient, {
queryKey: key,
initialData: 5,
staleTime: 1000,
})

const unsubscribe1 = observer1.subscribe(() => undefined)

const observer2 = new QueryObserver(queryClient, {
queryKey: key,
initialData: 5,
staleTime: 2000,
})

const unsubscribe2 = observer2.subscribe(() => undefined)

expect(consoleMock).toHaveBeenCalledTimes(1)
expect(consoleMock).toHaveBeenCalledWith(
`Multiple observers with different staleTimes are attached to the this query: ["${key}"]. The staleTime of the query will be determined by the last observer.`,
)
unsubscribe1()
unsubscribe2()
consoleMock.mockRestore()
})

it('should not warn when multiple observers have different staleTimes but not mounted at the same time', async () => {
const consoleMock = vi.spyOn(console, 'error')
consoleMock.mockImplementation(() => undefined)
const key = queryKey()
const observer1 = new QueryObserver(queryClient, {
queryKey: key,
initialData: 5,
staleTime: 1000,
})

const unsubscribe1 = observer1.subscribe(() => undefined)

unsubscribe1()

const observer2 = new QueryObserver(queryClient, {
queryKey: key,
initialData: 5,
staleTime: 2000,
})

const unsubscribe2 = observer2.subscribe(() => undefined)

expect(consoleMock).toHaveBeenCalledTimes(0)
unsubscribe2()
consoleMock.mockRestore()
})
})
13 changes: 13 additions & 0 deletions packages/query-core/src/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,19 @@ export class Query<

const time = timeUntilStale(this.state.dataUpdatedAt, staleTime)

if (process.env.NODE_ENV !== 'production') {
const staleTimes = this.observers.map((observer) =>
this.#resolveStaleTime(observer.options.staleTime),
)
staleTimes.push(staleTime)

if (new Set(staleTimes).size > 1) {
console.error(
`Multiple observers with different staleTimes are attached to the this query: ${this.queryHash}. The staleTime of the query will be determined by the last observer.`,
)
}
}

const newInvalidated = time === 0
if (this.state.isInvalidated !== newInvalidated) {
this.#dispatch({
Expand Down

0 comments on commit 3ae6bff

Please sign in to comment.