Skip to content

Commit

Permalink
fix: make sure initial data is used when switching queries (#944)
Browse files Browse the repository at this point in the history
  • Loading branch information
boschni committed Aug 31, 2020
1 parent 64be573 commit 211edc0
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
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

1 comment on commit 211edc0

@vercel
Copy link

@vercel vercel bot commented on 211edc0 Aug 31, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.