DocsLearn

Loading data

Data from the server comes later than the first draw. Show a placeholder until it does, keep it current as it changes, and clean up after yourself when the component goes.

In this lesson

  • how to load something and show a placeholder until it comes;
  • how to keep a list live from the database;
  • how to run code when a component is shown, and when it goes.

Something that comes later

useEffect runs after the component is drawn: start loading there, and keep the answer in state. Until it comes, show a placeholder.

import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";

// Stands in for a request to the server: an answer after a moment.
const fetchWeather = (city) => new Promise((done) => setTimeout(() => done({ city, degrees: 12 + city.length }), 600));

export default function App() {
  const [city, setCity] = useState("Brussels");
  const [weather, setWeather] = useState(null);
  useEffect(() => {
    let current = true;
    setWeather(null);
    fetchWeather(city).then((w) => current && setWeather(w));
    // An answer overtaken by a newer question is dropped.
    return () => { current = false; };
  }, [city]);
  return (
    <div className="grid gap-3">
      <div className="flex gap-2">
        {["Brussels", "Lisbon", "Oslo"].map((c) => (
          <Button key={c} variant={c === city ? "secondary" : "ghost"} onClick={() => setCity(c)}>{c}</Button>
        ))}
      </div>
      {weather ? <p>{weather.city}: {weather.degrees} °C</p> : <p className="text-muted-foreground">Loading…</p>}
    </div>
  );
}
  • What it depends on is listed: [city]. Changing the city asks again.
  • The function it returns runs before the next ask, and when the component goes: here it drops an answer that came too late.

Lists that stay live

In an app, @sluurp/react gives a collection’s records, kept current as anyone changes them, in this tab or any other:

components/todos.tsx
"use client";
import { useLive } from "@sluurp/react";

export function Todos() {
  const { rows, ready } = useLive("todos", { sort: "created_at" });
  if (!ready) return <p>Loading…</p>;
  return (
    <ul>
      {rows.map((t) => <li key={t.id}>{t.title}</li>)}
    </ul>
  );
}

A page in routes/ can also load its data on the server, before it’s sent, so the first draw already has it: const { items } = await server.collection("todos").list(). See Server components and Sync.

When a component is shown, and when it goes

useEffect with an empty list runs once, after the first draw. What it returns runs when the component goes: a timer stopped, a listener taken away.

import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";

function Clock() {
  const [now, setNow] = useState(new Date());
  useEffect(() => {
    const timer = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(timer);
  }, []);
  return <p className="font-mono tabular-nums">{now.toLocaleTimeString()}</p>;
}

export default function App() {
  const [shown, setShown] = useState(true);
  return (
    <div className="grid gap-3">
      <Button variant="secondary" onClick={() => setShown((s) => !s)}>{shown ? "Hide" : "Show"} the clock</Button>
      {shown && <Clock />}
    </div>
  );
}

That’s the Learn section. Next: build something real with sluurp create, or read how data and rules work.

View as Markdown