sveltelean Query
Version v0.2.0

Example

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

Member and teammates

The example runs in the browser.

Requests the server received

  1. 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}
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

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));