T
TanStack3y ago
dependent-tan

How can I `useQueryClient` outside a Svelte component?

I'm using the excellent svelte-query – thanks so much Lachlan! I'd like to abstract my query functions and define them in .ts files away from my .svelte files. As part of this, I want to use onMutate and onSuccess functions to do optimistic updates etc, e.g.:
onSettled: () => {
const queryClient = useQueryClient();
queryClient.invalidateQueries(['lobby', gameID]);
},
onSettled: () => {
const queryClient = useQueryClient();
queryClient.invalidateQueries(['lobby', gameID]);
},
The problem seems to be with calling useQueryClient() outside of a Svelte component. I get this error:
Error: Function called outside component initialization
mutation.ts:250 Error: Function called outside component initialization
at get_current_component (index.mjs:984:15)
at getContext (index.mjs:1076:12)
at getQueryClientContext (context.js?v=3319898c:5:20)
at useQueryClient (useQueryClient.js?v=3319898c:3:25)
Error: Function called outside component initialization
mutation.ts:250 Error: Function called outside component initialization
at get_current_component (index.mjs:984:15)
at getContext (index.mjs:1076:12)
at getQueryClientContext (context.js?v=3319898c:5:20)
at useQueryClient (useQueryClient.js?v=3319898c:3:25)
Is there any better way to access the queryClient inside my .ts files or inside my query's callback functions?
3 Replies
dependent-tan
dependent-tanOP3y ago
One extra wrinkle: when using hot reloading, if I hit save then I stop seeing this error! That is, if I refresh the page I do see the error. Weird, right? This means it's still a problem as I can't get it to work in the production build.
correct-apricot
correct-apricot3y ago
From NOT a Svelete user. Are you able to export/share the queryClient which is initialized? This line below
export const queryClient = new QueryClient()
export const queryClient = new QueryClient()
This is the queryClient that'll be passed into the QueryClientProvider If so, then you should be able to use this queryClient variable with instantiated QueryClient class, outside of a .svelete file I'd guess. With regards to optimistic updates, according to the docs, you should use the useQueryClient hook to get the queryClient from context, outside of the onSettled, onSuccess, onMutate calls. Lines 21 and 48 of the screenshot below.
No description
dependent-tan
dependent-tanOP3y ago
The useQueryClient hook doesn't appear to be happy inside my .ts files for some reason (gives the error shown above), but I've moved the instantiation of the new QueryClient() out of the .svelte file into a .ts file which makes it importable (can't export from .svelte file and import into a .ts file afaict) ... and that seems to work! I'm just importing that and using it inside my onSettled calls etc – it seems to work as expected now. Thank you 😄

Did you find this page helpful?