Step 3 of 7. Read visitors, sessions, pageviews, bounce rate and session duration with @spoar/client and show them as tiles.
This step reads data back. @spoar/client gives one scope per project; links such as period and traffic narrow it, and a read method at the end sends the request.
6 files, 5 new
12345678910111213141516171819202122import { createClient } from "@spoar/client";import type { ProjectScope } from "@spoar/client";
import type { Settings } from "./settings";import { trimEndpoint } from "./settings";
/** * @name createProject * @description One `@spoar/client` scope over the configured project. A public project needs no * token, so `token` is left out when empty. * * @example * const project = createProject(settings); * const stats = await project.period("7d").stats(); */export function createProject(settings: Settings): ProjectScope { const api = createClient({ endpoint: trimEndpoint(settings.endpoint), ...(settings.token ? { token: settings.token } : {}), }); return api.project(settings.project); }The scope over one project. Every read in this tutorial starts here.
123456789101112131415164 unmodified lines2122232420252627282930import { useEffect, useMemo } from "react";
import { createTracking } from "./analytics";import { createProject } from "./api";import { StatsTiles } from "./components/stats-tiles";import { settings } from "./settings";
export function App() { const project = useMemo(() => createProject(settings), []); const analytics = useMemo(() => createTracking(settings), []); const scope = useMemo(() => project.period("7d").traffic("human"), [project]); const scopeKey = "7d|human";
useEffect(() => () => void analytics.shutdown(), [analytics]);
return (4 unmodified lines Set <code>BUN_PUBLIC_DASHBOARD_PROJECT</code> in <code>.env.local</code> to your project id. </p> ) : ( <h1>{settings.project}</h1> <StatsTiles scope={scope} scopeKey={scopeKey} /> )} </main> </div> );}Links return a new scope and leave the old one as it was. human() and traffic("human") leave out traffic scored as bots.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import type { ClientError } from "@spoar/client";import type { ReactNode } from "react";
import type { Read } from "../use-read";
type Props<Value> = { title: string; read: Read<Value> & { retry: () => void }; isEmpty: (value: Value) => boolean; empty: string; skeleton: ReactNode; children: (value: Value) => ReactNode;};
function Failure({ error, onRetry }: { error: ClientError; onRetry: () => void }) { return ( <div className="failure" role="alert"> <code>{error.code}</code> <p>{error.message}</p> <button type="button" className="ghost" onClick={onRetry}> Retry </button> </div> );}
export function ReadFrame<Value>({ title, read, isEmpty, empty, skeleton, children,}: Props<Value>) { const value = read.value; let body: ReactNode; if (read.status === "error" && value === null) { body = <Failure error={read.error} onRetry={read.retry} />; } else if (value === null) { body = skeleton; } else if (isEmpty(value)) { body = <p className="empty">{empty}</p>; } else { body = children(value); } return ( <section className={`card${read.status === "loading" ? " is-loading" : ""}`}> <header className="card-head"> <h2>{title}</h2> {read.status === "error" && value !== null ? ( <button type="button" className="ghost warn" onClick={read.retry}> {read.error.code}, retry </button> ) : null} </header> {body} </section> );}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import type { ProjectScope, StatsResponse } from "@spoar/client";
import { formatChange, formatCount, formatDuration, formatPercent } from "../format";import { useRead } from "../use-read";import { ReadFrame } from "./read-frame";
type Props = { scope: ProjectScope; scopeKey: string };
type Tile = { label: string; metric: keyof StatsResponse["data"]; format: (value: number) => string; invert?: boolean;};
const tiles: Tile[] = [ { label: "Visitors", metric: "visitors", format: formatCount }, { label: "Sessions", metric: "sessions", format: formatCount }, { label: "Pageviews", metric: "pageviews", format: formatCount }, { label: "Bounce rate", metric: "bounceRate", format: formatPercent, invert: true }, { label: "Session duration", metric: "sessionDurationMs", format: formatDuration },];
function direction(change: number | null, invert: boolean | undefined) { if (change === null || change === 0) return "flat"; const up = change > 0; return up !== Boolean(invert) ? "good" : "bad";}
export function StatsTiles({ scope, scopeKey }: Props) { const stats = useRead(() => scope.stats(), [scopeKey]); return ( <ReadFrame title="Overview" read={stats} isEmpty={(value) => value.data.visitors.value === 0 && value.data.pageviews.value === 0} empty="No traffic in this range." skeleton={ <dl className="tiles"> {tiles.map((tile) => ( <div key={tile.metric} className="tile"> <dt>{tile.label}</dt> <dd className="skeleton">0</dd> </div> ))} </dl> } > {(value) => ( <dl className="tiles"> {tiles.map((tile) => { const compared = value.data[tile.metric]; return ( <div key={tile.metric} className="tile"> <dt>{tile.label}</dt> <dd>{tile.format(compared.value)}</dd> <span className={`change ${direction(compared.change, tile.invert)}`}> {formatChange(compared.change)} </span> </div> ); })} </dl> )} </ReadFrame> );}One request for all five numbers, each with its change against the period before.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 });const whole = new Intl.NumberFormat("en");
/** * @name formatCount * @description Formats a count: whole numbers under ten thousand, compact above (12.3K, 1.2M). * * @example * formatCount(12345); // "12.3K" */export function formatCount(value: number) { return value < 10_000 ? whole.format(value) : compact.format(value);}
/** * @name formatPercent * @description Formats a share from 0 to 1 as a whole percentage. * * @example * formatPercent(0.412); // "41%" */export function formatPercent(share: number) { return `${Math.round(share * 100)}%`;}
/** * @name formatDuration * @description Formats milliseconds as seconds under a minute, otherwise minutes and seconds. * * @example * formatDuration(95_000); // "1m 35s" */export function formatDuration(ms: number) { const seconds = Math.round(ms / 1000); if (seconds < 60) return `${seconds}s`; return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;}
/** * @name formatChange * @description Formats a change ratio as a signed percentage, or "new" when there is no previous * value to compare with. * * @example * formatChange(0.191); // "+19%" */export function formatChange(change: number | null) { if (change === null) return "new"; const percent = Math.round(change * 100); if (percent === 0) return "0%"; return `${percent > 0 ? "+" : ""}${percent}%`;}123456789101112131415161718192021222324252627282930313233343536373839404142import type { ClientError, ClientResult } from "@spoar/client";import { useEffect, useState } from "react";
export type Read<Value> = | { status: "loading"; value: Value | null } | { status: "ready"; value: Value } | { status: "error"; error: ClientError; value: Value | null };
/** * @name useRead * @description Runs one read from `@spoar/client` whenever `key` changes and holds its `Result` * as loading, ready or error state. The previous value stays visible while a new read loads, a * stale response is dropped, and nothing here throws. * * @example * const stats = useRead(() => scope.stats(), [key]); * if (stats.status === "error") return <Failure error={stats.error} onRetry={stats.retry} />; */export function useRead<Value>(read: () => ClientResult<Value>, key: readonly unknown[]) { const [state, setState] = useState<Read<Value>>({ status: "loading", value: null }); const [attempt, setAttempt] = useState(0);
useEffect(() => { let current = true; setState((previous) => ({ status: "loading", value: previous.value })); void read().then((result) => { if (!current) return; if (result.ok) setState({ status: "ready", value: result.value }); else setState((previous) => ({ status: "error", error: result.error, value: previous.value })); }); return () => { current = false; }; }, [...key, attempt]);
function retry() { setAttempt((count) => count + 1); }
return { ...state, retry };}Reads return a Result instead of throwing: ok with a value, or not ok with a ClientError that has a code and a message.
A response for an older key arrives after a newer one was requested, so it is dropped.
ReadFrame gives every panel the same four states: a skeleton while the first read loads, an error with a retry button, an empty message, and the data.
The same read against this site's own project:
Each metric has a value and a change, the ratio against the previous period of the same length. change is null when that period had nothing to compare with, and the tile shows "new".
A period such as 7d ends at the start of today in UTC, so today's visits are not counted yet. Use between(from, to) to read up to now. Read client lists every link and read.
Next, chart visitors.