Skip to content

Async work

A signal can hold a typed union of loading, success, and error states. Start the request in the component or in an effect that follows a changing parameter. Update the signal when the request settles. Bind child text or a conditional region to that signal.

This example simulates a request. Turn on Simulate a failure before loading, or close the request while it is pending to exercise the cleanup.

A request owned by a branch

Loading the example…

View source
async.ts
import { mount, onCleanup, signal, when } from "min-reactive-framework";
import type { Dispose } from "min-reactive-framework";
import { button, div, label, input, p } from "min-reactive-framework/html";
import type { DemoLanguage } from "../example-language.js";
type Result = { status: "loading" | "ready" | "error" };
function simulateRequest(signal: AbortSignal, fail: boolean): Promise<void> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (fail) reject(new Error("Simulated request failure"));
else resolve();
}, 700);
signal.addEventListener(
"abort",
() => {
clearTimeout(timer);
reject(signal.reason);
},
{ once: true },
);
});
}
export function run(target: HTMLElement, lang: DemoLanguage): Dispose {
const ru = lang === "ru";
const open = signal(false);
const fail = signal(false);
function RequestPanel() {
const controller = new AbortController();
const result = signal<Result>({ status: "loading" });
onCleanup(() => controller.abort());
void simulateRequest(controller.signal, fail.value).then(
() => {
if (!controller.signal.aborted) result.value = { status: "ready" };
},
() => {
if (!controller.signal.aborted) result.value = { status: "error" };
},
);
return p({ id: "request-state", role: "status", class: "mr-demo-panel" }, () => {
switch (result.value.status) {
case "loading":
return ru ? "Загрузка…" : "Loading…";
case "ready":
return ru ? "Данные получены." : "Data received.";
case "error":
return ru ? "Запрос завершился ошибкой." : "The request failed.";
}
});
}
return mount(target, () =>
div(
{ class: "mr-demo-stack" },
label(
{ class: "mr-demo-checkbox" },
input({
type: "checkbox",
checked: fail,
disabled: open,
on: {
input: (_event, field) => {
fail.value = field.checked;
},
},
}),
ru ? "Сымитировать ошибку" : "Simulate a failure",
),
button(
{
type: "button",
on: {
click: () => {
open.value = !open.value;
},
},
},
() =>
open.value
? ru
? "Закрыть запрос"
: "Close request"
: ru
? "Загрузить данные"
: "Load data",
),
when(open, RequestPanel),
),
);
}

Use onCleanup when a request belongs to a component or a branch. When a request follows a signal, return cleanup from the effect so the previous request is cancelled before a replacement starts. After await, check whether the signal has been aborted before committing the result.

import { effect, signal } from "min-reactive-framework";
type Result =
{ state: "loading" } | { state: "ready"; text: string } | { state: "error"; text: string };
const query = signal("start");
const result = signal<Result>({ state: "loading" });
const stop = effect(() => {
const value = query.value;
const controller = new AbortController();
result.value = { state: "loading" };
void fetch("/api/search?q=" + encodeURIComponent(value), { signal: controller.signal })
.then(async (response) => {
if (!response.ok) throw new Error(String(response.status));
const text = await response.text();
if (!controller.signal.aborted) result.value = { state: "ready", text };
})
.catch((error: unknown) => {
if (!controller.signal.aborted) result.value = { state: "error", text: String(error) };
});
return () => controller.abort();
});

Replace /api/search with your endpoint. Reads before await belong to the synchronous effect. Values read after an async boundary belong to the later turn.