Query Recipes
Dependent queries
A query whose params need the answer of another returns undefined until they exist. No effect, no flag, no request with a missing input.
Markdown version of this page, for assistants (Markdown for AI)
On this page
Example
Pick a member; the teammates list waits for the member's team.
The example runs in the browser.
Requests the server received
- None yet.
Code
<!-- src/routes/members/[id]/+page.svelte -->
<script lang="ts">
import { createQuery } from '@svelte-lean/query';
import { getMember, listMembers } from '$api/members';
let id = $state(1);
const member = createQuery(getMember, () => ({ id }));
// Waits for the member's team; `undefined` sends nothing and creates no cache entry.
const teammates = createQuery(listMembers, () =>
member.data ? { team: member.data.team } : undefined
);
</script>
<label>
Member
<select bind:value={id}>
<option value={1}>Amara Okafor</option>
<option value={2}>Jonas Lindqvist</option>
<option value={3}>Mei Tanaka</option>
</select>
</label>
{#if member.data}
<p>{member.data.name} works in {member.data.team}.</p>
{/if}
{#if !member.data}
<p>Waiting for the member.</p>
{:else if teammates.loading}
<p>Loading teammates…</p>
{:else}
<ul>
{#each teammates.data?.rows ?? [] as mate (mate.id)}
<li>{mate.name}</li>
{/each}
</ul>
{/if}How it works
- The params function returns
undefined: no key, no entry, no request;blockedis'when'andinfo.statusis'idle'. - When
member.dataarrives the function re-runs and returns{ team }: one request, causeparams. - Another member of the same team gives equal params: the key is the same, nothing is sent.
- Two requests one after the other are the cost of the data model. When the server can answer both in one response, one endpoint saves the second round trip.
Variations
A missing route param
TypeScript
// A route param that may be missing: not ready until it is there.
const member = createQuery(getMember, () => (params.id ? { id: Number(params.id) } : undefined));Related
- Reading: a missing input,
whenandload(). - Load when a dialog opens