# Dependent queries

> A second query that waits for an input from the first, without a waterfall of effects.

Page: https://svelte-lean.vercel.app/query/recipes/dependent-queries · Markdown: https://svelte-lean.vercel.app/query/recipes/dependent-queries.md · Index: https://svelte-lean.vercel.app/llms.txt

A query whose params need the answer of another returns undefined until they exist. No effect, no flag, no request with a missing input.

## Example

Pick a member; the teammates list waits for the member's team.

```svelte
<!-- 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}
```

The component shown, against an in-memory server that answers after a fixed delay.

## How it works

- The params function returns `undefined`: no key, no entry, no request; `blocked` is `'when'` and `info.status` is `'idle'`.
- When `member.data` arrives the function re-runs and returns `{ team }`: one request, cause `params`.
- 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

```ts
// 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](https://svelte-lean.vercel.app/query/reading.md): a missing input, `when` and `load()`.
- [Load when a dialog opens](https://svelte-lean.vercel.app/query/recipes/dialog.md)
