Skip to main content

Vanilla TypeScript

A todo list and a lookup form built with plain DOM code. @hyper-fetch/core does not need React or any other framework: you create a client, describe requests, and call send().

beginnervanillasendtypescript
import "@picocss/pico/css/pico.min.css";
import "./styles.css";
import { getTodo, getTodos } from "./api";

// Plain DOM: a static skeleton, then `textContent` for everything that comes from the API.
const root = document.getElementById("root")!;
root.innerHTML = `
<main class="container">
<hgroup>
<h1>Todos</h1>
<p>HyperFetch without a framework: <code>request.send()</code> and the response object.</p>
</hgroup>
<div class="grid-2">
<section>
<h2>Latest todos</h2>
<ul id="todos" class="list" aria-busy="true"></ul>
</section>
<section>
<h2>Look up a todo</h2>
<form id="lookup" role="group">
<input name="todoId" type="number" min="1" value="1" aria-label="Todo id" required />
<button type="submit">Send</button>
</form>
<small class="muted">Ids above 254 do not exist. Try 9999 to see an error response.</small>
<article id="result">
<dl class="response">
<dt>success</dt><dd data-field="success">-</dd>
<dt>status</dt><dd data-field="status">-</dd>
<dt>data</dt><dd data-field="data">-</dd>
<dt>error</dt><dd data-field="error">-</dd>
<dt>time</dt><dd data-field="time">-</dd>
</dl>
</article>
</section>
</div>
</main>
`;

const todoList = root.querySelector<HTMLUListElement>("#todos")!;
const form = root.querySelector<HTMLFormElement>("#lookup")!;
const result = root.querySelector<HTMLElement>("#result")!;
const field = (name: string) => result.querySelector<HTMLElement>(`[data-field="${name}"]`)!;

const listItem = (text: string) => {
const item = document.createElement("li");
item.textContent = text;
return item;
};

const loadTodos = async () => {
// send() never rejects. Network errors, timeouts and 4xx/5xx come back in `error`.
const { data, error } = await getTodos.send({ queryParams: { limit: 5 } });
todoList.removeAttribute("aria-busy");

if (error || !data) {
todoList.replaceChildren(listItem(`Could not load todos: ${error?.message}`));
return;
}

todoList.replaceChildren(...data.todos.map((todo) => listItem(`${todo.completed ? "✓" : "○"} ${todo.todo}`)));
};

form.addEventListener("submit", async (event) => {
event.preventDefault();
const todoId = Number(new FormData(form).get("todoId"));

result.setAttribute("aria-busy", "true");
// `:todoId` in the endpoint makes `params` required and typed here.
const response = await getTodo.send({ params: { todoId } });
result.removeAttribute("aria-busy");

field("success").textContent = String(response.success);
field("status").textContent = String(response.status);
field("data").textContent = response.data ? `#${response.data.id} ${response.data.todo}` : "null";
field("error").textContent = response.error ? response.error.message : "null";
field("time").textContent = `${response.responseTimestamp - response.requestTimestamp} ms`;
});

loadTodos();
Run locallynpx tiged BetterTyped/hyper-fetch/examples/vanilla/basic hyper-fetch-vanilla-basic && cd hyper-fetch-vanilla-basic && npm install && npm run dev
What it shows
  1. createClient and createRequest work the same with or without a UI framework.
  2. send() takes typed params and queryParams and returns a promise with the response.
  3. The response object carries data, error, success, status and timestamps for every call.
  4. Errors resolve, they do not throw. A 404 comes back as a response with a typed error.

How it works​

  1. api.ts creates one client with createClient({ url }) and two requests. getTodo also sets the error generic, so response.error is typed as the { message } body dummyjson returns for a missing todo.
  2. main.ts writes a static HTML skeleton and fills it with textContent, so nothing from the API is parsed as HTML.
  3. loadTodos() calls getTodos.send({ queryParams: { limit: 5 } }) on start. The values passed to send() apply to that call only.
  4. The lookup form calls getTodo.send({ params: { todoId } }). :todoId in the endpoint makes params required, so TypeScript flags a call without it.
  5. Every field of the response is printed: success and status, then data or error, and the time between requestTimestamp and responseTimestamp. Try id 9999 to see a 404 come back as a normal response.
const response = await getTodo.send({ params: { todoId } });
if (response.error) console.log(response.status, response.error.message);

send() also accepts lifecycle callbacks such as onRequestStart, onDownloadProgress and onResponse when you need to react before the promise settles.

When to use it
  • Scripts, web components or apps built with a framework that has no HyperFetch bindings.
  • Code that runs outside components, such as route loaders, workers or Node scripts.

Summary

You sent typed requests with send() from plain TypeScript and read data, error, success and status from the response. The same core API powers the React hooks.