How to deal with contextual and non serizalizable query key ? #6099
Replies: 2 comments 11 replies
-
Some explorations later, I have found the "meta" option of the useQuery hook const UserInfoOK3: React.FC<{ userId: number }> = ({ userId }) => {
const httpClient = useCustHttpClient();
const { data, status } = useQuery({
queryKey: ["userInfo", userId],
queryFn: ({ meta }: { meta: WithHttpClientMeta }) =>
api(meta.httpClient, userId),
meta: {
httpClient
}
});
return (
<div>
{status}: {data}
</div>
);
}; There's no, however, strong typing of the meta object, neither isolation. |
Beta Was this translation helpful? Give feedback.
11 replies
-
Sorry for the long delay. To conclude, I followed your suggestion to implement queryKeyHashFn. I use this code: import { hashQueryKey, useQuery } from "@tanstack/react-query";
...
...
const { data } = useQuery({
queryKey: ["data", serviceScope, config],
queryKeyHashFn: (key) => {
const fixKeys = key.map((k) => {
if (k instanceof ServiceScope) {
return serviceScope.id.toString();
} else {
return k;
}
});
return hashQueryKey(fixKeys);
},
queryFn: () => {
return getData({ serviceScope, config });
},
}); This way, I keep the original Thanks for the suggestion ! |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I'm working on a project requiring some custom HTTP client to fetch API data. The project is actually a plugin of a 3rd party application that injects the plugin using a DOM node and a render method. The render method get a custom http client as parameter. There's no "global" object I can use to get such http client.
This works well, but it breaks react query dependency array check, because the class is not serializable (cyclic dependency).
I created a code sandbox repro to illustrate:
https://codesandbox.io/s/thirsty-shamir-p4y89x?file=/src/App.tsx
Both query client and custom Http client are provider to the react tree using context providers:
This allows me to write component that requires both context objects:
But this code fails because the httpClient variable cannot be serialized :
TypeError: cyclic object value
.If I don't put this variable in the dependency array, the code runs but the eslint rule yell because of the missing dependency (this can be removed, but it may hide also other dependency miss.
I can trick react query using something like:
this works at runtime, eslint rule is doing its job because the argument is out of the query function. But this requires a lot more non obvious code to add everytime an API is required.
Is there any proper way to handle such situation ?
Is there any way to "extend" the query client with arbitrary data ? Something like a custom "context" that may be set to query client ?
thanks for advise!
Beta Was this translation helpful? Give feedback.
All reactions