-
Hi, I recently upgraded from a previous version (3.13.12) to the most recent version (3.16.0), and noticed a typechecking error while compiling my TypeScript project, which wasn't here when I upgraded react-query. After some tweaking on the react-query version, I noticed that the version 3.15.2 was the culprit with the changes related to #2200 and how are queryKeys are handled at runtime. Here is an example of my source-code, which is very similar to this famous react-query TypeScript guide: // This is inside an `API.ts` file which contains every fetch calls for my endpoints.
// Those functions are called inside `useQuery`.
type CharactersResponse = {
accountName: string;
characters: Character[];
};
type Params = {
queryKey: [string, { accountName?: string; token?: string }];
};
export const getCharacters = (params: Params): Promise<CharactersResponse> => {
const [, { accountName, token }] = params.queryKey;
if (!accountName || !token) {
throw new Error('Unexpected undefined values, which are meant to be defined at this time of execution.');
}
return fetch(`/my-endpoint?accountName=${accountName}&token=${token}`, {
method: 'GET',
});
}; // SetupSession.tsx is a React component which consume react-query and the getCharacters API endpoint.
export const SetupSession: React.FC<SetupSession> = () => {
// ...
const { accountName, token } = useContext(UserContext);
const fetchCharacters = useQuery(['fetchCharacters', { accountName, token }], getCharacters);
// ^^^^^^^^^^^^^
}; The following error appears under the
It looks like the issue is coming from react-query which changes the queryKey type from The actual fix for me after spending a few hours on this, is to keep using the version 3.15.1. I'm also posting this here as I'm not actually sure it's an issue with the library and I believe can be a real implementation issue when following the blog post mentioned earlier (which is the top 1 search hit for "react-query typescript"). Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
sorry for your troubles. It compiles fine if you inline the function. You can then see that the inferred type is
you can see that here: https://codesandbox.io/s/react-query-starting-point-forked-v7gc3?file=/src/App.tsx:268-370 |
Beta Was this translation helpful? Give feedback.
sorry for your troubles. It compiles fine if you inline the function. You can then see that the inferred type is
QueryFunctionContext
, so if you use that to type it, it also works if you extract it to a function:you can see that here: https://codesandbox.io/s/react-query-starting-point-forked-v7gc3?file=/src/App.tsx:268-370