Skip to content

load — Data Fetching ​

load creates a reactive resource that automatically fetches data and refetches when its key changes.

load<T, K>(key, fetcher) ​

tsx
import { load } from "@hedystia/view";

const resource = load(
  () => val(userId),                      // key: accessor, refetches when it changes
  async (id) => fetch(`/api/users/${id}`).then((r) => r.json()), // fetcher
);

Parameters ​

ParameterDescription
keyAccessor function () => K. When the returned value changes, the fetcher re-runs
fetcherasync (key: K) => T — the fetch function

Resource Properties ​

PropertyTypeDescription
dataAccessor<T | undefined>The fetched data
loadingAccessor<boolean>Whether a fetch is in progress
errorAccessor<Error | undefined>The error, if any
stateAccessor<string>"pending", "ready", "refreshing", or "errored"
readybooleanGetter — true when state is "ready"

State Transitions ​

"pending" → "ready"      (successful first fetch)
"pending" → "errored"    (failed first fetch)
"ready"   → "refreshing" (key changed, refetching)
"refreshing" → "ready"   (refetch succeeded)
"refreshing" → "errored" (refetch failed)

JSX Example ​

tsx
import { sig, load, mount } from "@hedystia/view";

interface User {
  id: number;
  name: string;
  email: string;
}

function UserCard() {
  const [userId, setUserId] = sig(1);

  const user = load(
    userId,
    async (id): Promise<User> => {
      const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
      return res.json();
    },
  );

  return (
    <div>
      <div>
        <button onClick={() => setUserId(userId() - 1)}>Previous</button>
        <button onClick={() => setUserId(userId() + 1)}>Next</button>
      </div>

      {() => {
        if (user.loading()) return <p>Loading...</p>;
        if (user.error()) return <p>Error: {user.error()!.message}</p>;

        const data = user.data();
        if (!data) return <p>No user</p>;

        return (
          <div>
            <h2>{data.name}</h2>
            <p>{data.email}</p>
          </div>
        );
      }}
    </div>
  );
}

mount(UserCard, document.getElementById("root")!);


When `userId` changes, the resource automatically aborts the previous fetch and starts a new one.

## Cancellation and stale responses

The fetcher receives a native `AbortSignal` as its second argument. Forward it to `fetch` to stop superseded network work:

```ts
const resource = load(
  () => val(userId),
  async (id, signal) => {
    const response = await fetch(`/api/users/${encodeURIComponent(id)}`, { signal });
    if (!response.ok) throw new Error(`Request failed: ${response.status}`);
    return response.json();
  },
);

Changing the key aborts the previous request. Late successes and errors are ignored even if a fetcher does not honor the signal. A resource created inside a reactive owner aborts its request when that owner is disposed. One-argument fetchers continue to work. Retrying clears the previous error and sets loading while keeping the last successful data. An AbortError from the active fetcher is reported as an error unless the resource's own signal was cancelled.