Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 39 ยท SolidStart and Routing

Route Data: query and createAsync

Load data for routes with Solid Router query and createAsync, understand request deduplication, preloading and revalidation, and see how it works with SSR.

For data a single component fetches on its own, createResource is fine. For data that belongs to a page, Solid Router offers a better pair: query and createAsync. They solve problems that hand-written resources do not:

  • Preloading: start fetching as soon as the user hovers a link, before the page renders.
  • Deduplication: if three components ask for the same data, only one request is made.
  • Caching and revalidation: results are kept briefly and can be refreshed by name after a change.
  • Server rendering: the data is fetched on the server, streamed, and reused by the browser without a second request.

query and createAsync come from @solidjs/router (SolidStart includes it). They need the router and a bundler, so the real code below is read-only. The live example is a small stand-in written in plain Solid that reproduces the caching and revalidation behavior so you can see what the real functions do for you. Older router versions called query by the name cache; check the docs for the version you install.

Defining a query

A query is a function wrapped with a key. The key identifies a cached result: same function, same arguments, same cache entry.

TypeScript
// src/lib/queries.ts
import { query } from "@solidjs/router";

export const getPosts = query(async () => {
  "use server";                         // runs on the server in SolidStart
  return db.posts.findMany({ orderBy: { createdAt: "desc" } });
}, "posts");

export const getPost = query(async (id: string) => {
  "use server";
  const post = await db.posts.find(id);
  if (!post) throw new Error("Post not found");
  return post;
}, "post");

The second argument is the base key ("posts", "post"). For queries with arguments, the router combines the key with the arguments, so getPost("1") and getPost("2") are cached separately. ("use server" is covered in server functions; in a plain Solid app, the function would call fetch.)

Reading it with createAsync

Inside a component, wrap the query call in createAsync:

TSX
import { createAsync } from "@solidjs/router";
import { Show, For, Suspense } from "solid-js";

export default function Posts() {
  const posts = createAsync(() => getPosts());

  return (
    <Suspense fallback={<p>Loading posts...</p>}>
      <ul>
        <For each={posts()}>{(p) => <li>{p.title}</li>}</For>
      </ul>
    </Suspense>
  );
}

createAsync takes a function, tracks the signals it reads (for example a route param) and runs again when they change, like a resource with a source. It suspends like a resource, so it works with Suspense, transitions and ErrorBoundary exactly as in the earlier lessons. Unlike createResource, it hands the caching to query, and in SolidStart the result is serialised from the server to the browser, so hydration does not fetch again.

A dynamic route reads its parameter reactively:

TSX
// src/routes/blog/[slug].tsx
const params = useParams();
const post = createAsync(() => getPost(params.slug));

Preloading

A route can export a preload function that Solid Router calls when navigation starts (on link hover or click), in parallel with downloading the route's code:

TSX
export const route = {
  preload: ({ params }) => getPost(params.slug),
};

The call to the query fills the cache. When the page component later runs createAsync(() => getPost(params.slug)), the data is already in flight or ready, so the page renders without a waterfall. Without preload, the fetch would only start after the code arrives and the component renders.

sequenceDiagram
  participant U as User
  participant R as Router
  participant C as Query cache
  U->>R: Hover a link
  R->>C: preload: getPost("hello")
  C-->>C: fetch starts
  U->>R: Click
  R->>C: component calls getPost("hello")
  C-->>R: same promise, no new request

Preload and the component ask for the same key, so there is one request.

Deduplication and revalidation

The cache gives you two behaviors you would otherwise build yourself:

  1. Deduplication: calls with the same key within a short window share one promise.
  2. Revalidation: after you change data, ask the router to refresh by key.
TypeScript
import { revalidate } from "@solidjs/router";

await savePost(data);
revalidate(getPosts.key);       // every createAsync reading posts refreshes
revalidate(getPost.keyFor("1")); // or one specific entry

Actions (next lesson) revalidate all queries automatically after they finish, unless you tell them otherwise.

A stand-in that shows the behavior

The stand-in below implements a tiny query with a keyed cache, counts the "network" calls, and offers a revalidate. Press "Show another view" a few times and see one request. Then edit on the "server" and revalidate.

Stand-in: keyed cache, dedupe and revalidate

However many views you add, the call counter stays at 1 because they all use the same key. After "Edit on server", the screen is stale until you revalidate; then the counter goes up by one and every view shows the new title.

Choosing between createResource and createAsync

createResource query + createAsync
Where Any component, local data Route-level and shared data
Dedupe and cache No Yes, by key
Preload before render No Yes, via route.preload
Refresh refetch() of one resource revalidate(key) for all readers
SSR serialisation Yes Yes, designed for it

A fair rule: use createResource for self-contained widgets, and queries for anything a page or several components share.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What identifies a cache entry for a query?

    getPost('1') and getPost('2') use the same base key but different arguments, so they are cached separately.
  2. 2. What is the purpose of a route's preload function?

    It warms the query cache so the page can render without waiting for a fetch to begin.
  3. 3. How do you refresh every createAsync that reads the posts query after a change?

    revalidate invalidates entries by key and every reader refetches.
  4. 4. Why is createAsync good for SSR?

    Data fetched while rendering on the server is sent along with the HTML.

Summary

  • query(fn, key) caches and deduplicates by key and arguments; createAsync reads it reactively and suspends.
  • Export route.preload to start fetching on hover or click, avoiding waterfalls.
  • revalidate refreshes by key; actions do this automatically.
  • In SolidStart, results fetched on the server are serialised to the client.
  • Use createResource for local widget data and queries for shared page data.

Next: Server Functions and Actions