# Async state

> Read when a value comes from a request. Load a promise into a value while it is observed, map its failure into the value, and keep the status and retry policy in the request library.

## Example

Sorus ships no loading flag, refetch, cache, or Suspense hook; a request
library, such as TanStack Query, owns those, and Sorus holds the answer. The
chat's profile request is loaded into `$profile`, with a status union the
application writes once.

```ts
import { Computed } from "@frondruntime/sorus";
import { app } from "./realm.ts";

// The application's own status type: Sorus ships none.
interface Profile {
  readonly id: string;
  readonly name: string;
}

type ProfileLoad =
  | { readonly state: "loading" }
  | { readonly state: "loaded"; readonly profile: Profile }
  | { readonly state: "failed"; readonly error: unknown };

// The request runs while something observes $profile, and its signal aborts
// when the last observer leaves. The failure is mapped into the value, so
// the screen shows it; a rejection left unmapped goes to the realm's onError.
const $profile = Computed.fromPromise<ProfileLoad>(
  app,
  (signal) =>
    fetch(profileUrl, { signal })
      .then((response) => {
        if (!response.ok) throw new Error(`profile: the server answered ${response.status}`);
        return response.json();
      })
      .then((body): ProfileLoad => ({ state: "loaded", profile: toProfile(body) }))
      // After the parse, so a body that is not a profile fails too.
      .catch((error: unknown): ProfileLoad => ({ state: "failed", error })),
  { state: "loading" },
  { name: "profile" },
);

// The composer's placeholder, empty until the profile arrives.
const $placeholder = Computed.make(
  app,
  (read) => {
    const load = read($profile);
    return load.state === "loaded" ? `Message as ${load.profile.name}` : "";
  },
  { name: "placeholder" },
);
```

## Rules

- `load` starts the request and passes it `signal`, never returns a started
  promise: the last observer leaving aborts it, and each new observation
  requests again.
- Map a failure the screen shows into the value, inside `load`. A rejection
  left unmapped goes to the realm's `onError`, and the value keeps what it
  held.
- Hold a value that must keep its answer across screens with
  `Source.observe` ([Lifecycles](../state/lifecycles.md)). Unobserved, it
  resets to `initial`, and the next observer requests again.
- Keep the status, retry, and refetch policy in the request library or in
  plain code. Sorus holds the answer; the library decides when to ask.

## Answers

| Call | Answers |
| --- | --- |
| `Computed.fromPromise(realm, load, initial, { equals?, name? })` | A read-only computed value. `load(signal)` runs from the first observer and is aborted by the last; the value is `initial` until it resolves and again once unobserved. |

## With Effect

`Program.fromEffect` answers the same kind of value over an Effect, interrupted
when the last observer leaves: see [Programs](../effect/programs.md).

## See also

- [Lifecycles](../state/lifecycles.md): `Source.observe` and `Source.onObserved`.
- [Live data](./live-data.md): a request whose answer replaces rows.
- [Saving state](./saving.md): a result that must be saved or restored.
- [Programs](../effect/programs.md): `Program.fromEffect`.
