Skip to content
Merged
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
7 changes: 4 additions & 3 deletions src/core/queryObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,9 +277,10 @@ export class QueryObserver<TResult, TError> {

// Remove the initial data when there is an existing query
// because this data should not be used for a new query
const config = prevQuery
? { ...this.config, initialData: undefined }
: this.config
const config =
this.config.keepPreviousData && prevQuery
? { ...this.config, initialData: undefined }
: this.config

const newQuery = config.queryCache!.buildQuery(config.queryKey, config)

Expand Down
32 changes: 32 additions & 0 deletions src/react/tests/useQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -698,6 +698,38 @@ describe('useQuery', () => {
consoleMock.mockRestore()
})

it('should keep initial stale and initial data when the query key changes', async () => {
const key = queryKey()
const states: QueryResult<{ count: number }>[] = []

function Page() {
const [count, setCount] = React.useState(0)
const state = useQuery([key, count], () => ({ count: 10 }), {
initialStale: () => false,
initialData: () => ({ count }),
})
states.push(state)

React.useEffect(() => {
setTimeout(() => setCount(1))
}, [])

return null
}

render(<Page />)

await waitFor(() => expect(states.length).toBe(5))

expect(states).toMatchObject([
{ data: { count: 0 } },
{ data: { count: 0 } },
{ data: { count: 1 } },
{ data: { count: 1 } },
{ data: { count: 10 } },
])
})

it('should retry specified number of times', async () => {
const key = queryKey()
const consoleMock = mockConsoleError()
Expand Down