Skip to content

Commit

Permalink
fix(query): set error to null when going to loading state (#3106)
Browse files Browse the repository at this point in the history
to be aligned with the types, as `loading` cannot have an `error` set.
  • Loading branch information
TkDodo committed Dec 17, 2021
1 parent 2054f5b commit 3981f52
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/core/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,10 @@ export class Query<
fetchMeta: action.meta ?? null,
isFetching: true,
isPaused: false,
status: !state.dataUpdatedAt ? 'loading' : state.status,
...(!state.dataUpdatedAt && {
error: null,
status: 'loading',
}),
}
case 'success':
return {
Expand Down
76 changes: 76 additions & 0 deletions src/react/tests/useQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4505,4 +4505,80 @@ describe('useQuery', () => {

consoleMock.mockRestore()
})

it('should have no error in loading state when refetching after error occurred', async () => {
const consoleMock = mockConsoleError()
const key = queryKey()
const states: UseQueryResult<number>[] = []
const error = new Error('oops')

let count = 0

function Page() {
const state = useQuery(
key,
async () => {
await sleep(10)
if (count === 0) {
count++
throw error
}
return 5
},
{
retry: false,
}
)

states.push(state)

if (state.isLoading) {
return <div>status: loading</div>
}
if (state.error instanceof Error) {
return (
<div>
<div>error</div>
<button onClick={() => state.refetch()}>refetch</button>
</div>
)
}
return <div>data: {state.data}</div>
}

const rendered = renderWithClient(queryClient, <Page />)

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

fireEvent.click(rendered.getByRole('button', { name: 'refetch' }))
await waitFor(() => rendered.getByText('data: 5'))

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

expect(states[0]).toMatchObject({
status: 'loading',
data: undefined,
error: null,
})

expect(states[1]).toMatchObject({
status: 'error',
data: undefined,
error,
})

expect(states[2]).toMatchObject({
status: 'loading',
data: undefined,
error: null,
})

expect(states[3]).toMatchObject({
status: 'success',
data: 5,
error: null,
})

consoleMock.mockRestore()
})
})

1 comment on commit 3981f52

@vercel
Copy link

@vercel vercel bot commented on 3981f52 Dec 17, 2021

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.