Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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/yummy-rooms-read.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/react-query': patch
---

Fixed isFetchedAfterMount in cases where initialData is applied
43 changes: 43 additions & 0 deletions packages/query-core/src/__tests__/query.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1304,4 +1304,47 @@ describe('query', () => {
data: 'data1',
})
})

test('should not increment dataUpdateCount when setting initialData on prefetched query', async () => {
const key = queryKey()
const queryFn = vi.fn().mockImplementation(() => 'fetched-data')

// First prefetch the query (creates query without data)
queryClient.prefetchQuery({
queryKey: key,
queryFn,
})

const query = queryCache.find({ queryKey: key })!
expect(query.state.data).toBeUndefined()
expect(query.state.dataUpdateCount).toBe(0)

// Now create an observer with initialData
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn,
initialData: 'initial-data',
})

// The query should now have the initial data but dataUpdateCount should still be 0
// since this was not fetched data but initial data
expect(query.state.data).toBe('initial-data')
expect(query.state.dataUpdateCount).toBe(0)

// Get the initial state as captured by the observer
const result = observer.getCurrentResult()
expect(result.data).toBe('initial-data')
expect(result.isFetchedAfterMount).toBe(false) // This should be false since no actual fetch occurred

// Now trigger a refetch through the observer to simulate real-world usage
await observer.refetch()

// After actual fetch, dataUpdateCount should increment
expect(query.state.dataUpdateCount).toBe(1)
expect(query.state.data).toBe('fetched-data')

// And isFetchedAfterMount should now be true
const updatedResult = observer.getCurrentResult()
expect(updatedResult.isFetchedAfterMount).toBe(true)
})
})
4 changes: 3 additions & 1 deletion packages/query-core/src/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -636,7 +636,9 @@ export class Query<
const newState = {
...state,
data: action.data,
dataUpdateCount: state.dataUpdateCount + 1,
dataUpdateCount: action.manual && state.data === undefined
? state.dataUpdateCount // Don't increment for initial data
: state.dataUpdateCount + 1,
dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),
error: null,
isInvalidated: false,
Expand Down
Loading