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
35 changes: 22 additions & 13 deletions packages/query-core/src/queryObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export class QueryObserver<
#refetchIntervalId?: ManagedTimerId
#currentRefetchInterval?: number | false
#trackedProps = new Set<keyof QueryObserverResult>()

#everSubscribed = false
constructor(
client: QueryClient,
public options: QueryObserverOptions<
Expand Down Expand Up @@ -95,7 +95,7 @@ export class QueryObserver<
protected onSubscribe(): void {
if (this.listeners.size === 1) {
this.#currentQuery.addObserver(this)

this.#everSubscribed = true
if (shouldFetchOnMount(this.#currentQuery, this.options)) {
this.#executeFetch()
} else {
Expand Down Expand Up @@ -176,7 +176,7 @@ export class QueryObserver<
}

const mounted = this.hasListeners()

// Fetch if there are subscribers
if (
mounted &&
Expand All @@ -191,7 +191,7 @@ export class QueryObserver<
}

// Update result
this.updateResult()
this.updateResult(mounted ? undefined : false)

// Update stale interval if needed
if (
Expand Down Expand Up @@ -228,11 +228,17 @@ export class QueryObserver<
TQueryKey
>,
): QueryObserverResult<TData, TError> {
const query = this.#client.getQueryCache().build(this.#client, options)
const query = this.#client.getQueryCache().build(this.#client, options)

const result = this.createResult(
query,
options,
!this.#everSubscribed || this.hasListeners(),
)

const result = this.createResult(query, options)

if (shouldAssignObserverCurrentProperties(this, result)) {
if (shouldAssignObserverCurrentProperties(this, result)) {

// this assigns the optimistic result to the current Observer
// because if the query function changes, useQuery will be performing
// an effect where it would fetch again.
Expand All @@ -250,8 +256,8 @@ export class QueryObserver<
// When keeping the previous data, the result doesn't change until new
// data arrives.
this.#currentResult = result
this.#currentResultOptions = this.options
this.#currentResultState = this.#currentQuery.state
this.#currentResultOptions = this.options
this.#currentResultState = this.#currentQuery.state
}
return result
}
Expand Down Expand Up @@ -439,6 +445,7 @@ export class QueryObserver<
TQueryData,
TQueryKey
>,
optimistic = true,
): QueryObserverResult<TData, TError> {
const prevQuery = this.#currentQuery
const prevOptions = this.options
Expand All @@ -461,7 +468,7 @@ export class QueryObserver<
if (options._optimisticResults) {
const mounted = this.hasListeners()

const fetchOnMount = !mounted && shouldFetchOnMount(query, options)
const fetchOnMount = optimistic && !mounted && shouldFetchOnMount(query, options)

const fetchOptionally =
mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions)
Expand Down Expand Up @@ -642,12 +649,12 @@ export class QueryObserver<
return nextResult
}

updateResult(): void {
updateResult(optimistic?: boolean): void{
const prevResult = this.#currentResult as
| QueryObserverResult<TData, TError>
| undefined

const nextResult = this.createResult(this.#currentQuery, this.options)
const nextResult = this.createResult(this.#currentQuery, this.options, optimistic)

this.#currentResultState = this.#currentQuery.state
this.#currentResultOptions = this.options
Expand Down Expand Up @@ -737,10 +744,12 @@ export class QueryObserver<
}

// Then the cache listeners
if (this.hasListeners()) {
this.#client.getQueryCache().notify({
query: this.#currentQuery,
type: 'observerResultsUpdated',
})
}
})
}
}
Expand Down Expand Up @@ -832,4 +841,4 @@ function shouldAssignObserverCurrentProperties<

// basically, just keep previous properties if nothing changed
return false
}
}
42 changes: 42 additions & 0 deletions packages/react-query/src/__tests__/useQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5980,6 +5980,48 @@ describe('useQuery', () => {

expect(renders).toBe(1)
})
it('should not report isFetching when subscribed is false and no fetch is running', async () => {
const key = queryKey()

const states: Array<UseQueryResult<string>> = []

function Page() {
const [subscribed, setSubscribed] = React.useState(true)

const result = useQuery({
queryKey: key,
queryFn: () => Promise.resolve('data'),
subscribed,
})

states.push(result)

return (
<div>
<span>
{result.fetchStatus} {String(result.isFetching)}
</span>

<button onClick={() => setSubscribed(false)}>unsubscribe</button>
</div>
)
}

const rendered = renderWithClient(queryClient, <Page />)

await vi.advanceTimersByTimeAsync(0)

rendered.getByText('idle false')

fireEvent.click(rendered.getByRole('button', { name: 'unsubscribe' }))

await vi.advanceTimersByTimeAsync(0)

const latest = states[states.length - 1]!

expect(latest.fetchStatus).toBe('idle')
expect(latest.isFetching).toBe(false)
})
})

it('should have status=error on mount when a query has failed', async () => {
Expand Down