T
TanStack2y ago
like-gold

Is it possible to create queries outside of context?

I have a load function in a +layout.ts I'm running a adapter-static, so all this is purely on the browser.
import { queries } from '$lib/api';
import { createQuery } from '@tanstack/svelte-query';
import type { LayoutLoad } from './$types';

export const load: LayoutLoad = async ({ params: { accountId }, parent }) => {
const { queryClient } = await parent();
const accountQueryDefinition = queries.accounts.id(accountId);
return {
accountId,
accountQueryDefinition,
accountQuery: createQuery(accountQueryDefinition, queryClient),
};
};
import { queries } from '$lib/api';
import { createQuery } from '@tanstack/svelte-query';
import type { LayoutLoad } from './$types';

export const load: LayoutLoad = async ({ params: { accountId }, parent }) => {
const { queryClient } = await parent();
const accountQueryDefinition = queries.accounts.id(accountId);
return {
accountId,
accountQueryDefinition,
accountQuery: createQuery(accountQueryDefinition, queryClient),
};
};
I'd like to send the query through as a store to the pages. Unfortunately, it looks like @tanstack/svelte-query/context.ts has a call getIsRestoringContext = (): Readable<boolean> which results in a call to getContext in svelte - which throws.
app.js:24 Error: Function called outside component initialization
at get_current_component (lifecycle.js:11:32)
at getContext (lifecycle.js:141:9)
at getIsRestoringContext (context.js:19:25)
at useIsRestoring (useIsRestoring.js:3:12)
at createBaseQuery (createBaseQuery.js:9:25)
at createQuery (createQuery.js:4:12)
at load (+layout.ts:13:17)
at async load_node (client.js?v=e2855009:530:14)
app.js:24 Error: Function called outside component initialization
at get_current_component (lifecycle.js:11:32)
at getContext (lifecycle.js:141:9)
at getIsRestoringContext (context.js:19:25)
at useIsRestoring (useIsRestoring.js:3:12)
at createBaseQuery (createBaseQuery.js:9:25)
at createQuery (createQuery.js:4:12)
at load (+layout.ts:13:17)
at async load_node (client.js?v=e2855009:530:14)
Is this a bug in tanstacks context.ts, or just not possible with the design?
2 Replies
like-gold
like-goldOP2y ago
I do have a a QueryClientProvider set in the root layout - and everything works well - just trying to avoid the boilerplate of recreating the query at the top of each page, instead of just getting it from the exposed export let data; The client itself is created in my root +layout.ts and passed down to the QueryClientProvider via exposed export let data;, and also available in the child load functions
like-gold
like-goldOP2y ago
Well, that was a fun experience. Did my first PR with gitpod 👍 https://github.com/TanStack/query/pull/6193
GitHub
fix(svelte-query): getIsRestoringContext not throw by softgripper ·...
Calling getIsRestoringContext could throw an error. Now it can't. The types usage is improved, and the method has a testcase relates #6188

Did you find this page helpful?