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.:
The problem seems to be with calling useQueryClient() outside of a Svelte component. I get this error:
Is there any better way to access the queryClient inside my .ts files or inside my query's callback functions?3 Replies
dependent-tanOP•3y 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•3y ago
From NOT a Svelete user.
Are you able to export/share the queryClient which is initialized? This line below
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.
dependent-tanOP•3y 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 😄