To finish an app’s backbone, the concepts you’ve learned must line up on a single page. This lesson covers both layout composition and data fetching in one consistent sequence.
Key terms
- Page component: The top-level component for a route; it defines layout regions and kicks off store connections and data requests.
onMount: A Svelte hook that runs after the component attaches to the DOM—safe timing for client-only API calls.- API: The set of rules for exchanging data with a server, usually a
fetch('/api/...')call returning JSON. - Loading/error state: Flags that tell the user whether data is in flight or failed so they understand what’s happening.
Core ideas
The page component owns the full screen. It splits the view into header, content, sidebar, and so on, and declares where data loads start. onMount fires once the DOM exists, which means it’s the right place for browser-only fetch calls. APIs are the contracts between client and server; wiring them with a loading → success → error flow keeps the UI honest. If you make these states a habit, teammates always know where data comes from.
Code examples
Start with a service status board to see the basic flow.
<script>
import { onMount } from 'svelte';
let services = [];
let loading = true;
async function fetchStatus() {
loading = true;
const res = await fetch('/api/status');
services = await res.json();
loading = false;
}
onMount(fetchStatus);
</script>
{#if loading}
<p>Loading status…</p>
{:else}
<ul>
{#each services as service (service.id)}
<li>
<strong>{service.name}</strong> — {service.healthy ? 'Healthy' : 'Under maintenance'}
</li>
{/each}
</ul>
{/if}
fetchStatus keeps both the loading copy and the real data in sync. The same structure can power a campus server dashboard or a club project monitor. Now pair the page with a central store:
// src/lib/stores/articles.js
function createArticlesStore() {
const { subscribe, set, update } = writable({
list: [],
selected: null,
loading: false,
error: null
});
async function load() {
update((state) => ({ ...state, loading: true, error: null }));
try {
const res = await fetch('/api/articles');
const data = await res.json();
set({ list: data, selected: data[0] ?? null, loading: false, error: null });
} catch (err) {
set({ list: [], selected: null, loading: false, error: err.message });
}
}
function select(article) {
update((state) => ({ ...state, selected: article }));
}
return { subscribe, load, select };
}
export const articlesStore = createArticlesStore();
The root page calls load, the list component renders $articlesStore.list, and the detail component shows $articlesStore.selected. Loading, error, and empty states all live in one store.
Why it matters
Real apps often show a summary list alongside a detail panel. When the page root is clearly defined, collaborators know exactly where data originates. Making loading/error/success states routine prevents blank screens during maintenance.
Practice checklist
- Follow along: build the service status board and trigger
onMountto fetch data. - Extend it: create
articlesStoreand add a list-plus-detail layout. - Debug: if data disappears, confirm the
$articlesStoreprefix and error handling insideload. - Completion criteria: refreshing still shows synced data in both the list and the detail panel.
Wrap-up
Pages connect layout, stores, and API requests. Master this flow and later routing or layout topics won’t shake you.
💬 댓글
이 글에 대한 의견을 남겨주세요