Skip to content

Commit

Permalink
fix: only stop finalizing if we were previously in pending state
Browse files Browse the repository at this point in the history
this makes sure we can read stale data from entries when switching to them immediately
  • Loading branch information
TkDodo committed Oct 12, 2024
1 parent c1f5016 commit 96661a7
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
15 changes: 8 additions & 7 deletions packages/query-core/src/queryObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -598,12 +598,10 @@ export class QueryObserver<

if (this.options.experimental_prefetchInRender) {
const finalizeThenableIfPossible = (thenable: PendingThenable<TData>) => {
if (query.queryHash === prevQuery.queryHash) {
if (nextResult.status === 'error') {
thenable.reject(nextResult.error)
} else if (nextResult.data !== undefined) {
thenable.resolve(nextResult.data)
}
if (nextResult.status === 'error') {
thenable.reject(nextResult.error)
} else if (nextResult.data !== undefined) {
thenable.resolve(nextResult.data)
}
}

Expand All @@ -623,7 +621,10 @@ export class QueryObserver<
switch (prevThenable.status) {
case 'pending':
// Finalize the previous thenable if it was pending
finalizeThenableIfPossible(prevThenable)
// and we are still observing the same query
if (query.queryHash === prevQuery.queryHash) {
finalizeThenableIfPossible(prevThenable)
}
break
case 'fulfilled':
if (
Expand Down
11 changes: 9 additions & 2 deletions packages/react-query/src/__tests__/useQuery.promise.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -791,6 +791,7 @@ describe('useQuery().promise', () => {

it('should show correct data when switching between cache entries without re-fetches', async () => {
const key = queryKey()
let suspenseRenderCount = 0

function MyComponent(props: { promise: Promise<string> }) {
const data = React.use(props.promise)
Expand All @@ -799,6 +800,7 @@ describe('useQuery().promise', () => {
}

function Loading() {
suspenseRenderCount++
return <>loading..</>
}
function Page() {
Expand Down Expand Up @@ -827,14 +829,19 @@ describe('useQuery().promise', () => {
await waitFor(() => rendered.getByText('loading..'))
await waitFor(() => rendered.getByText('test0'))

expect(suspenseRenderCount).toBe(1)

fireEvent.click(rendered.getByText('inc'))
await waitFor(() => rendered.getByText('loading..'))

await waitFor(() => rendered.getByText('test1'))

fireEvent.click(rendered.getByText('dec'))
expect(suspenseRenderCount).toBe(2)

fireEvent.click(rendered.getByText('dec'))
await waitFor(() => rendered.getByText('test0'))

// no more suspending when going back to test0
expect(suspenseRenderCount).toBe(2)
})

it('should not resolve with intermediate data when keys are switched', async () => {
Expand Down

0 comments on commit 96661a7

Please sign in to comment.