Skip to content

Loaders ​

Loaders: the data a component awaits in <script setup>, which the Rust app loads.

A component that needs data the page's props do not carry awaits a loader at the top of its <script setup>, as Vue's server would await any promise there. A loader is a function declared with defineLoader: in the browser it fetches, and on the server the Rust app implements it. The compiler reads the declaration for the types of its arguments and its result, and writes a loaders module with a struct for each one's call and a Loaders trait with a method for each, which the app implements.

ts
// components/loaders.ts
import { defineLoader } from "ferrovue";

export interface Post {
  title: string;
  tags: string[];
}

export const loadPost = defineLoader("loadPost", async (slug: string, lang?: string): Promise<Post> => {
  const response = await fetch(`/api/posts/${encodeURIComponent(slug)}?lang=${encodeURIComponent(lang ?? "en")}`);
  return (await response.json()) as Post;
});

export const loadViews = defineLoader("loadViews", async (slug: string): Promise<number> => {
  const response = await fetch(`/api/views/${encodeURIComponent(slug)}`);
  return (await response.json()) as number;
});
vue
<!-- PostPage.vue -->
<script setup lang="ts">
import { loadPost } from "./loaders";
import ViewCount from "./ViewCount.vue";

const props = defineProps<{ slug: string; lang?: string }>();
const post = await loadPost(props.slug, props.lang);
</script>

<template>
  <article>
    <h1>{{ post.title }}</h1>
    <ul>
      <li v-for="tag in post.tags" :key="tag">{{ tag }}</li>
    </ul>
    <ViewCount :slug="slug" />
  </article>
</template>

<!-- ViewCount.vue -->
<script setup lang="ts">
import { loadViews } from "./loaders";

const props = defineProps<{ slug: string }>();
const views = await loadViews(props.slug);
</script>

<template>
  <p>{{ views }} views</p>
</template>

A loader's name, the first argument of defineLoader, is its name in Rust and its key in the page's payload, so it is unique in the project. The result may be destructured into plain names (const { title, tags } = await loadPost(props.slug)), and a component may await several loaders, one after the other, each call's arguments read from the props, from constants, from computeds and from the results awaited before it. await Promise.all([loadPost(slug), loadViews(slug)]) awaits several at once, its results bound to an array of names (const [post, views] = …): the render asks for every call of the array before it stops where one result is missing, so the app runs them together, as Vue's server does.

The Rust side ​

Every component that awaits a loader, or renders one that does, takes a &Loads after its other parameters; such a component is not an island, since the browser needs the results to hydrate it (see the client). The app implements the generated Loaders trait, one method per loader, given the call's arguments as a struct, and renders through the generated load:

rust
use std::convert::Infallible;
use generated::loaders::{self, LoadPost, LoadViews, Loaders};
use generated::{post_page, types::Post};

struct Site;

impl Loaders for Site {
    type Error = Infallible;

    async fn load_post(&self, call: LoadPost) -> Result<Post<'static>, Infallible> {
        // A database query, or a call to another service.
        Ok(Post::new(format!("About {}", call.slug), ["rust", "vue"]))
    }

    async fn load_views(&self, call: LoadViews) -> Result<i64, Infallible> {
        Ok(call.slug.len() as i64)
    }
}

let props = post_page::Props::new("ferrovue");
let rendering = loaders::load(&Site, |loads| {
    let mut out = String::new();
    post_page::render(&mut out, &props, loads);
    // The results the client hydrates from, after the components that read them.
    loads.script_into(&mut out);
    out
});
// In an async handler: let page = rendering.await?;
assert_eq!(
    page.unwrap(),
    concat!(
        r#"<article><h1>About ferrovue</h1><ul><!--[--><li>rust</li><li>vue</li><!--]--></ul><p>8 views</p></article>"#,
        r#"<script type="application/json" data-fv-loads>{"[\"loadPost\",\"ferrovue\"]":{"title":"About ferrovue","tags":["rust","vue"]},"[\"loadViews\",\"ferrovue\"]":8}</script>"#,
    )
);

A render stops where a component awaits a result it does not have yet, as Vue's server does, and load renders again once it has it: each call starts when Vue's would, the loaders of sibling components together, a component's children once its own loads have finished, and the awaits of one component in order. Every call finished by the time of a render is taken by it, so a page renders a few times at most, and a call is made once per key. The first loader to fail ends the render with a LoadError naming it and its key, as a rejected async setup rejects Vue's renderToString; the calls still running are dropped.

A page whose props or results the render may refuse (a date string browsers read differently, see errors_and_limits) renders with try_render in the closure, which returns Result<String, Refused>: try_render(…)? before loads.script_into(&mut out), and Ok(out) after. load then gives a Result of that Result, the loader's error outside and the Refused inside, once the render that read every result is done.

Since the closure runs once per render, it starts each one afresh: it makes its own String, and its own Teleports and Head when the page has them, so that what an earlier render collected is not written twice.

The generated module also has dispatch, which runs one call a render asks for with the app's method for it, for an app that drives load itself.

Dates ​

A loader's result may hold dates as a prop does: Promise<Date>, Promise<Date | null>, Promise<Date[]>, or an interface with date fields, lists and dictionaries of them. A date that is the result itself, or in a list, a dictionary or an optional of it, is a JsDate in Output; a date in an interface's field is the type dateType names. The payload writes each as its ISO string, an invalid one as NaN, and under dates where each loader's results hold dates:

text
{"[\"loadStock\",\"dune\"]":{"copies":3,"counted":"2024-06-01T00:00:00.000Z"},"dates":{"loadStock":[{"counted":1}]}}

provideLoads turns those back into Dates, so a component that awaits the loader in the browser hydrates from the dates the server rendered. A call the payload does not carry runs the loader in the browser, whose own code builds its dates, as new Date(json.counted) does from what an API returns.

Keys ​

A call's key is JSON.stringify([name, ...args]), which the client computes from the same call: loadPost("ferrovue") is ["loadPost","ferrovue"]. Arguments left out at the end, or given as undefined there, are left out of the key, as they are of the call, so loadPost("ferrovue") and loadPost("ferrovue", undefined) are one call; null is always written. A loader takes strings, numbers (Float for a fractional one) and booleans, which may be optional (lang?: string, an Option that is left out when None) or null (lang: string | null, written as null when None), so that both sides write the same key. A parameter may also be an interface of a .ts file whose fields are such values (loadFound(query: Query)): the call passes an object literal of its fields or a value of the interface, the loaders module holds it as a struct of its own (LoadFoundQuery), and the key writes its fields with their names sorted, as JSON.stringify writes an object whose keys are sorted, leaving out an optional one that is absent: loadFound({ term: "vue", lang: null }) is ["loadFound",{"lang":null,"term":"vue"}], whatever order the literal gives its keys.

A loader's result is its Output: the type its Promise<T> names, translated as a prop's type is (see props), with 'static lifetimes, since the result outlives the call.

The client ​

The payload Loads::script_into writes, <script type="application/json" data-fv-loads>, holds each result the render read, by its key. In the browser, a loader whose call's key is in the page's payload resolves to that result without running, so the component hydrates from what the server rendered; any other call runs the loader's function.

A component that awaits needs a <Suspense> above it on the client. mountPage and renderPage wrap the layout in one when the page carries results (suspense in their options says so otherwise); a <Suspense> writes no markup of its own, so the page hydrates as the server wrote it. For a navigation, readPage gives the next page's payloads as loads, which renderPage takes:

ts
const next = readPage(await (await fetch(href)).text());
current = await renderPage(Layout, parts, next.record, { loads: next.loads, previous: current });

provideLoads adds results by hand, and clearLoads forgets them. loadKey(name, args) is the key of a call.

Testing ​

A fixture gives each loader's result by its key under $loads, and the conformance suite renders the component with them, on the server and on the client:

json
{
  "slug": "ferrovue",
  "$loads": {
    "[\"loadPost\",\"ferrovue\"]": { "title": "About ferrovue", "tags": ["rust", "vue"] },
    "[\"loadViews\",\"ferrovue\"]": 8
  }
}

A call the fixture gives no result for fails the render on both sides.

What is refused ​

  • An await of anything but a loader's call (FV2001): the server has no other promise's result. A bare await that binds nothing is refused as any other setup statement is (FV0105).
  • A loader the compiler cannot read: a name that is not a string literal, a function that is not async, a parameter with a default, ...rest, a pattern or a type other than a string, number or boolean, a result type not declared as Promise<T> or one that may be undefined (FV2002 to FV2004). Return null for none.
  • Two loaders with one name, or names that are one Rust name (FV2005).
  • A call whose arguments do not match the parameters, or are spread (FV2006), and a result bound to a pattern other than a name or an object of plain names (FV2007).
  • A loader awaited anywhere but the top of <script setup>: in a computed, a function or the template. Those run synchronously on the server.