T
TanStack•13mo ago
ambitious-aqua

How to do dependent queries in svelte?

I can figure it out for the life of me 😦 best solution I have found is something like this:
let secondQuery = createQuery({
queryKey: ["s"],
queryFn: async () => {
...
},
enabled: () =>
!!$firstQuery.data &&
!$firstQuery.isFetching &&
!$firstQuery.isRefetching,
});

$: {
if ($firstQuery.isFetched && !$secondQuery.isFetched) {
$tleQuery.refetch();
}
}
let secondQuery = createQuery({
queryKey: ["s"],
queryFn: async () => {
...
},
enabled: () =>
!!$firstQuery.data &&
!$firstQuery.isFetching &&
!$firstQuery.isRefetching,
});

$: {
if ($firstQuery.isFetched && !$secondQuery.isFetched) {
$tleQuery.refetch();
}
}
3 Replies
correct-apricot
correct-apricot•13mo ago
You might need to derive your second query (passing in the first query) - see the link below. Otherwise the easiest way is to load the second query in a sub-component. This should be much simpler with svelte 5! https://tanstack.com/query/latest/docs/framework/svelte/reactivity
Reactivity | TanStack Query Svelte Docs
Svelte uses a compiler to build your code which optimises rendering. By default, components run once, unless they are referenced in your markup. To be able to react to changes in options you need to use stores. In the below example, the refetchInterval option is set from the variable intervalMs, which is bound to the input field. However, as t...
ambitious-aqua
ambitious-aquaOP•13mo ago
oooh. Okay. I don't love this, but it does get the job done and will fix a bunch other issues I had. Thanks! @Raytuzio You have helped a lot. This should be added to the docs as a way of handling dependent queries since that is very common use case
ratty-blush
ratty-blush•8mo ago
Did you figure this out? I can't figure it out.
let firstQuery = createQuery(...)

let secondQuery = createQuery($derived({
queryKey: ["BungieLatestNews", firstQuery?.apiKey],
let firstQuery = createQuery(...)

let secondQuery = createQuery($derived({
queryKey: ["BungieLatestNews", firstQuery?.apiKey],
i'm trying something like this no bueno will this only work in a svelte file?

Did you find this page helpful?