Skip to main content
Version: v10.0.0

Loading Data with Loaders

A loader tells a collection how to get rows from your backend. It is an existing request plus three facts the db cannot guess: how to read rows from the response, which filters and orders the endpoint accepts, and whether it reads records by key. With that, the db can turn any query into the right request, and run the rest of the query on the rows that come back.

This guide gives Teamboard's collections their loaders.

What you'll learn
  1. How to turn a request into a list loader or a by-key loader.
  2. How to read rows from wrapped responses with rows, and what a RowMismatch error means.
  3. How to declare the filters and orders an endpoint can send, and which ones it requires.
  4. How the db picks a loader when a collection has several, and how explain() shows the choice.
  5. How to load many records in one request with byKeys.
  6. How freshness, fixed filters and serverOnly fields keep answers correct.

Your first loaders​

Start with the two endpoints almost every resource has: one that lists and one that reads by id.

import { collection } from "@hyper-fetch/db";

const getTeamPosts = client.createRequest<{
response: { items: PostSummary[]; next: string | null };
queryParams?: { status?: "draft" | "published"; likes_gt?: number; title?: string; sort?: string };
}>()({ endpoint: "/teams/:teamId/posts" });

const getPost = client.createRequest<{ response: Post }>()({ endpoint: "/posts/:postId" });

const PostSummary = collection(PostSummarySchema, { key: "id" }).load(getTeamPosts, {
rows: (response) => response.items,
where: { teamId: { eq: (teamId) => ({ params: { teamId } }), required: true } },
});

const Post = collection(PostSchema, { key: "id" }).load(getPost, {
byKey: (id) => ({ params: { postId: id } }),
});
  • A list loader declares the conditions it can send in where. Each one returns a patch for the request: params, queryParams or payload, all checked against the request's own types.
  • A by-key loader declares byKey. It serves db.post.findOne(id).
  • The two endpoints return different shapes, so they feed different collections: summaries without body, and full posts. Rows in a collection are always complete.

Reading rows from a response​

Without rows, the response itself is the list of rows, or the row. Most APIs wrap lists, and some nest related records, so rows maps a response to complete rows:

const getFeed = client.createRequest<{
response: { data: { items: (Omit<PostSummary, "authorId"> & { author: User })[] } };
}>()({ endpoint: "/feed" });

collection(PostSummarySchema, { key: "id" }).load(getFeed, {
// Unwrap the list, and keep only the author's id on each row
rows: (response) => response.data.items.map(({ author, ...post }) => ({ ...post, authorId: author.id })),
});

The rows a loader produces must be exactly the schema's row type. A missing field, an extra field or a field of another type is a compile error:

const PostSummary = collection(PostSummarySchema, { key: "id" }).load(getTeamPosts, {
rows: (response) => response.items.map(({ likes, ...post }) => post),
});

createDb({ postSummary: PostSummary });
// `PostSummary` is a RowMismatch: the rows lack `likes`, so it has no collection methods

The error shows up where you use the result, not inside the callback. The loader returns a RowMismatch type that holds what it received and what it expected, so hover it to see the difference. The check sits in the return type on purpose: a check among the arguments would stop TypeScript from inferring the callbacks.

Nested records

Rows nested in a response, like the author above, can fill their own collection too. See Related Data and Joins.


Declaring filters and orders​

where lists, for each field, the operators the endpoint can serve. orderBy lists the fields it can sort by:

const PostSummary = collection(PostSummarySchema, { key: "id" }).load(getTeamPosts, {
rows: (response) => response.items,
where: {
// Part of the URL: the endpoint cannot work without it
teamId: { eq: (teamId) => ({ params: { teamId } }), required: true },
status: { eq: (status) => ({ queryParams: { status } }) },
likes: { gt: (likes) => ({ queryParams: { likes_gt: likes } }) },
},
orderBy: {
createdAt: (direction) => ({ queryParams: { sort: `createdAt:${direction}` } }),
},
});

Now a query decides what is sent. Conditions joined by a top-level and that the loader declares go to the backend, and the rest run on the returned rows:

import { and, eq, gt, inArray } from "@hyper-fetch/db";

db.postSummary.where((post) =>
and(
eq(post.teamId, "t1"), // sent: /teams/t1/posts
gt(post.likes, 10), // sent: ?likes_gt=10
inArray(post.authorId, ["u1", "u2"]), // not declared: filtered on the returned rows
),
);

Operators are one fixed vocabulary for every backend: eq, gt, gte, lt, lte, inArray, and, or and not. or and not always run on the client. How an operator is written for your backend, such as likes_gt=10, belongs to the loader.

Required filters​

required: true marks a filter the endpoint cannot work without, such as teamId in /teams/:teamId/posts. A query that does not set it as a top-level eq does not compile, because no loader could serve it:

useLiveQuery(db.postSummary.where((post) => gt(post.likes, 10)));
// No loader of `postSummary` can serve a query without `teamId`

One notation for the whole API​

When your API writes every operator the same way, declare the notation once in createDb and mark fields with true:

const db = createDb(
{ postSummary: PostSummary },
{
where: {
gt: (field, value) => ({ queryParams: { [`${field}_gt`]: value } }),
eq: (field, value) => ({ queryParams: { [field]: value } }),
},
orderBy: (field, direction) => ({ queryParams: { sort: `${field}:${direction}` } }),
},
);

collection(PostSummarySchema, { key: "id" }).load(getTeamPosts, {
rows: (response) => response.items,
where: {
teamId: { eq: (teamId) => ({ params: { teamId } }), required: true },
likes: { gt: true }, // ?likes_gt=10, from the db-wide notation
status: { eq: true }, // ?status=published
},
orderBy: { createdAt: true },
});

A loader's own mapping always wins over the db-wide notation.


Several loaders on one collection​

A collection can load through several endpoints. Add them in one chain:

const getPosts = client.createRequest<{ response: PostSummary[]; queryParams?: { authorId?: string } }>()({
endpoint: "/posts",
});

const PostSummary = collection(PostSummarySchema, { key: "id" })
// Loader 0: a team's posts
.load(getTeamPosts, {
rows: (response) => response.items,
where: { teamId: { eq: (teamId) => ({ params: { teamId } }), required: true } },
})
// Loader 1: posts across teams, by author
.load(getPosts, {
where: { authorId: { eq: (authorId) => ({ queryParams: { authorId } }) } },
});

For each query, the db considers the loaders whose required filters the query sets, and picks the one that can send most of its conditions. Ties go to the loader declared first, so the same query always gets the same plan:

db.postSummary.where((post) => eq(post.teamId, "t1")).explain();
// loader: 0, sent: teamId only loader 0 can send it

db.postSummary.where((post) => eq(post.authorId, "u1")).explain();
// loader: 1, sent: authorId loader 0 is out: the query sets no teamId

db.postSummary.where((post) => and(eq(post.teamId, "t1"), eq(post.authorId, "u1"))).explain();
// loader: 0, sent: teamId, local: authorId each sends one condition, so the first one wins

Adding a loader can change which loader serves an existing query. The plan is deterministic, explain() shows it, and HyperFlow shows it for every mounted query.

Conditions the endpoint applies on its own​

Some endpoints filter without being asked, such as a feed that only returns published posts. Declare it with fixed:

collection(PostSummarySchema, { key: "id" }).load(getTeamPosts, {
rows: (response) => response.items,
where: { teamId: { eq: (teamId) => ({ params: { teamId } }), required: true } },
fixed: { status: "published" },
});

The db applies the fixed filters to every query this loader serves:

  • A draft loaded somewhere else never shows up in the team feed.
  • A post moved back to draft by a socket event or a write leaves the feed at once.

Leave the condition undeclared and the db has no way to know that drafts do not belong in that list.


Reading by key, in batches​

A by-key loader with byKey reads one row per request. With byKeys, every key the mounted queries need in the same tick goes out as one request:

const getUsers = client.createRequest<{ response: User[]; queryParams?: { ids?: string[] } }>()({
endpoint: "/users",
});

const User = collection(UserSchema, { key: "id" }).load(getUsers, {
byKeys: (ids) => ({ queryParams: { ids } }),
});
// Twenty avatars on screen, one GET /users request with all twenty ids
const Avatar = ({ userId }: { userId: string }) => {
const { data: user } = useLiveQuery(db.user.findOne(userId));
return user ? <img src={user.avatarUrl} alt={user.name} /> : null;
};

Batching is what makes joins cheap: the authors of a whole list load in one request.


Freshness and memory​

A loaded subset decides on its own when to load again:

  • It stays fresh while syncs cover it with insert, update and delete events. A live subset never refetches just because time passed. See Real-time Sync.
  • Without full sync coverage, it is fresh for the request's staleTime, five minutes by default. Set it on the request, as you would for useFetch:
const getTeamPosts = client.createRequest<{ response: { items: PostSummary[] } }>()({
endpoint: "/teams/:teamId/posts",
staleTime: 30_000,
});
  • Stale subsets of mounted queries refetch when a query mounts, the window regains focus or the connection returns.
  • When no query uses a subset, it is kept for gcTime (five minutes by default, set in createDb), then released. Rows that no other subset holds leave the collection.

Requests run by loaders skip the core Cache, so each row is stored once. Deduplication, retries, authentication, plugins and setMock() still apply, because a loader is a plain request.


Fields the backend compares differently​

Answering locally only works when the client compares values the way the server does. Comparisons on the client are exact: strings by code point, dates by instant. If the backend sorts titles case-insensitively, or by locale, mark the field serverOnly:

collection(PostSummarySchema, { key: "id" }).load(getTeamPosts, {
rows: (response) => response.items,
where: {
teamId: { eq: (teamId) => ({ params: { teamId } }), required: true },
title: { eq: (title) => ({ queryParams: { title } }) },
},
serverOnly: ["title"],
});

Queries that filter or sort by title are then always sent to the backend instead of being answered from held rows, and their subsets never answer other queries. A missing serverOnly returns wrong rows with no request to correct them, so mark every field your backend compares in its own way.

serverOnly covers answers, not later writes: a row inserted by a socket event is still matched and sorted with exact comparisons. When the client cannot reproduce the server's matching at all, as with full-text search, use a server-only operator instead.

Which option do I need?
  • The response wraps or reshapes rows: rows.
  • The endpoint needs a value in its URL: where with required: true.
  • The endpoint filters or sorts on request: where and orderBy, or true with a db-wide notation.
  • The endpoint filters on its own: fixed.
  • The backend compares a field differently: serverOnly.
  • The endpoint reads by id: byKey, or byKeys when it accepts many ids.
  • The endpoint returns pages: cursor and page, or limit. See Pagination and Infinite Scroll.

Well loaded!

Teamboard's collections know how to reach the backend.

  • You can turn a request into a list loader or a by-key loader.
  • You can map wrapped responses with rows, and read a RowMismatch when they do not fit.
  • You can declare filters, orders and required filters, per loader or once for the whole API.
  • You can predict which loader a query uses, and check it with explain().
  • You can batch reads by key with byKeys.
  • You can keep answers correct with fixed, serverOnly and freshness.

Next steps​

Live Queries in React
Read collections with useLiveQuery: filters, orders, selections, single rows and loading states.