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
4 changes: 4 additions & 0 deletions docs/src/pages/reference/useQuery.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const {
isSuccess,
refetch,
remove,
reset,
status,
} = useQuery(queryKey, queryFn?, {
cacheTime,
Expand Down Expand Up @@ -228,3 +229,6 @@ const result = useQuery({
- If `cancelRefetch` is `true`, then the current request will be cancelled before a new request is made
- `remove: () => void`
- A function to remove the query from the cache.
- `reset: (options: { throwOnError: boolean, cancelRefetch: boolean }) => Promise<UseQueryResult>`
- A function to manually reset the query to its initial state.
- `options` are used to call `refetch` on the query after it is resetted.
76 changes: 76 additions & 0 deletions src/react/tests/useQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1032,6 +1032,82 @@ describe('useQuery', () => {
expect(states[3]).toMatchObject({ data: 2 })
})

it('should be able to reset a query', async () => {
const key = queryKey()
const states: UseQueryResult<number>[] = []
let count = 0

function Page() {
const state = useQuery(key, () => ++count)

states.push(state)

const { reset } = state

React.useEffect(() => {
setActTimeout(() => {
reset()
}, 5)
}, [reset])

return null
}

renderWithClient(queryClient, <Page />)

await sleep(20)

expect(states.length).toBe(5)
// Initial
expect(states[0]).toMatchObject({ data: undefined })
// Fetched
expect(states[1]).toMatchObject({ data: 1 })
// Reset
expect(states[2]).toMatchObject({ data: undefined })
// Initial (refetch)
expect(states[3]).toMatchObject({ data: undefined })
// Fetched
expect(states[4]).toMatchObject({ data: 2 })
})

it('should reset the query to its initial state', async () => {
const key = queryKey()
const states: UseQueryResult<number>[] = []
let count = 0

function Page() {
const state = useQuery(key, () => ++count, { initialData: 99 })

states.push(state)

const { reset } = state

React.useEffect(() => {
setActTimeout(() => {
reset()
}, 5)
}, [reset])

return null
}

renderWithClient(queryClient, <Page />)

await sleep(20)

expect(states.length).toBe(5)
// Initial
expect(states[0]).toMatchObject({ data: 99 })
// Fetched
expect(states[1]).toMatchObject({ data: 1 })
// Reset
expect(states[2]).toMatchObject({ data: 99 })
// Initial (refetch)
expect(states[3]).toMatchObject({ data: 99 })
// Fetched
expect(states[4]).toMatchObject({ data: 2 })
})

it('should share equal data structures between query results', async () => {
const key = queryKey()

Expand Down