Skip to content

Commit

Permalink
feat(react-query): better error in development mode to identify bad u…
Browse files Browse the repository at this point in the history
…seQuery calls (#6288)

* refactor(query-core): export isPlainObject

* refactor(useBaseQuery): dev error in case of bad argument

Mainly for project without TS. This helps tracking bad signature when migrating from v4 to v5.

* refactor(useQueryClient): dev error in case of bad queryClient

Mainly for project without TS. Make sure the queryClient passed as parameter is really a query. With the change of signature introduced by v5, queryOptions from useQuery could end up as queryClient due to how useBaseQuery works.

* revert: "refactor(useQueryClient): dev error in case of bad queryClient"

This reverts commit 9bedf21.

* refactor(useQuery): manual test to avoid export from query-core.

* refactor(useQuery test): TS ignore invalid call

---------

Co-authored-by: Guillaume Labat <[email protected]>
Co-authored-by: Dominik Dorfmeister <[email protected]>
  • Loading branch information
3 people authored Nov 4, 2023
1 parent 196cced commit 8a86182
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
21 changes: 21 additions & 0 deletions packages/react-query/src/__tests__/useQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6225,4 +6225,25 @@ describe('useQuery', () => {

await waitFor(() => rendered.getByText('Works'))
})

// For Project without TS, when migrating from v4 to v5, make sure invalid calls due to bad parameters are tracked.
it('should throw in case of bad arguments to enhance DevX', async () => {
// Mock console error to avoid noise when test is run
const consoleMock = vi
.spyOn(console, 'error')
.mockImplementation(() => undefined)

const key = queryKey()
const queryFn = () => 'data'

function Page() {
// Invalid call on purpose
// @ts-expect-error
useQuery(key, { queryFn })
return <div>Does not matter</div>
}

expect(() => render(<Page />)).toThrow('Bad argument type')
consoleMock.mockRestore()
})
})
8 changes: 8 additions & 0 deletions packages/react-query/src/useBaseQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ export function useBaseQuery<
Observer: typeof QueryObserver,
queryClient?: QueryClient,
) {
if (process.env.NODE_ENV !== 'production') {
if (typeof options !== 'object' || Array.isArray(options)) {
throw new Error(
'Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object',
)
}
}

const client = useQueryClient(queryClient)
const isRestoring = useIsRestoring()
const errorResetBoundary = useQueryErrorResetBoundary()
Expand Down

0 comments on commit 8a86182

Please sign in to comment.