---
title: "Resources and mutations"
description: "A resource is a reactive request to an app data source."
modificationDate: "2026-11-30"
---

> ## Documentation index
> Fetch the complete documentation index at: https://exact.expo.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Resources and mutations

<AgentInstructions>

## Submitting feedback

From the app's directory, read `bun exact.mjs feedback status`. Under `never`, keep no note.
Respect `EXACT_FEEDBACK=0` and do not change the policy.

Otherwise record specific, actionable feedback with:
`bun exact.mjs feedback note "Exact docs: https://exact.expo.dev/learn/contract-for-humans/resources-and-mutations: <what was wrong or missing>"`

The note goes to Expo only as that status allows. Include no secrets or personal data.

</AgentInstructions>

A resource is a reactive request to an app data source. The name reads as a value
of the declared type. When its inputs change, the runtime requests an answer
again. The source itself is implemented in TypeScript or Rust.

A mutation represents an explicitly requested operation. Its name reads as an
`option<T>`: `none` before an answer, `some(answer)` after one. `send` issues it;
ordinary assignment to `none` clears it and forgets an in-flight reply.

This complete Contract compiles; running it requires `loadItems` and `saveItem`
implementations in the app's data module:

```contract
shape Item
  id: string
  title: string
shape SaveResult
  ok: bool
  message: string

component Items
  state query = ""
  state notice = ""
  resource items = loadItems(query) as shape Item[]
  mutation saved as shape SaveResult refreshes items then afterSave
  action search(value: string)
    query = value
  action save(id: string)
    send saved = saveItem(id)
  action afterSave
    match saved
      case some(result)
        notice = result.message
      case none
        notice = ""
  action retry
    refresh items
  view
    column gap=8 padding=16
      input value=query input=search testId="query"
      if pending(items)
        text "Loading…"
      if failed(items)
        button press=retry testId="retry"
          text "Try again"
      for item in items key=item.id
        button press=save(item.id) testId=`item-${item.id}`
          text item.title
      text notice testId="notice"
```

The `refreshes items` clause asks `items` again when the reply lands. To show the
save before then, the data module exports an `overlay` for `loadItems` (the [agent
guide](https://exact.expo.dev/learn/contract-for-agents/data-requests-and-side-effects.md#optimistic-writes-the-overlay) has the pattern).
`then afterSave` runs a parameterless action in its own commit at the
host's next clock advance, once for every answer that landed before it, so it
reads the latest answer (the agent driver lands it at the end of the input
that settled the answer). It does not run for a failure that brought no answer,
and it must not send its own mutation. Do not use `then` as a general event queue.

`pending(resourceOrMutation)` asks whether a request is in flight.
`failed(resourceOrMutation)` asks whether its latest admitted request failed
without an answer. Both take the declared name. A failed mutation keeps its
previous value and runs no `then`; its next send clears the failure. A domain
error returned in a shaped answer is data, not a failed request.

`failure(resourceOrMutation)` says why: `none` until a request fails, then
`some` of a `Failure` record. Its `code` preserves a nonempty source `reason`,
such as a Snapback refusal's `SLOT_FULL`; otherwise it is an infrastructure
class (`offline`, `timeout`, `refused`, `shape`, `storage`, `error`; the grammar
says when each applies). `message` is for a developer; `reason` also retains
the source's domain code, or is empty.
The code and the reason are the same on every host; the message is not, so
branch on the code or the reason:

```contract
shape Item
  id: string

component Items
  resource items = loadItems() as shape Item[] else empty()
  derive banner = match failure(items) { case some(f) => f.code == "offline" ? "You're offline" : "Couldn't load items", case none => "" }
  view
    text banner testId="banner"
```

A data module reports `offline`, `timeout`, `refused` or `storage` only by letting
the `fetch` or storage rejection reach the runner; an error it throws of its own,
for an HTTP error status or invalid response, is `error`. A read source should
answer with a new value only when it has validated one. It should let a failed
refresh fail the resource so Exact can retain the prior answer and expose the
failure separately. A validated empty collection is a successful answer and may
replace the old collection. A source may return a shaped domain outcome when that
outcome is part of the read's meaning; it should not encode an unavailable read
as a successful empty value just to carry an error message.

Requests use newest-request-wins behavior: stale answers do not overwrite newer
requests. This determines which answer the runner adopts. It does not guarantee
that source work stops or undo storage operations already started. A failed
resource keeps its retained value or placeholder and clears pending. While a
replacement is pending, the view may still see the previous value, even after
the request's arguments change.

A private-data view should show a retained value only when its owner and
authorization match the current screen. An authenticated source must await the
app's shared current-session helper and verify that the session authorizes the
principal named by the request. The helper and auth generation are app code, not
Exact APIs. The app must advance its auth generation and clear its authorized
principal whenever the principal changes or signs out. A request tied to that
auth attempt should take the generation as a resource argument and return the
principal and generation as fields in its answer. The view should show private
data only when both fields match the currently authorized principal and
generation. Checking only the owner cannot distinguish signing into A, then B,
then A again. A pending session resource, or one that is merely not pending, does
not prove authorization. Put a non-secret account or tenant identifier in the
resource call; `signedIn: true` does not identify an account.

Before committing a refreshed session or shared owner-sensitive cache write,
recheck the auth generation when the write commits, including inside queued
work. When possible, store each owner's data under a separate cache key so a
valid result for account A can still populate A's cache while the user views
account B. If writes share a slot, guard the commit by owner and auth generation.
Do not discard a valid per-owner result only because another owner's request
became current. A changed input or explicit refresh allows another attempt.

A write log wants every send, not the newest. Declare the mutation `queue`
(`mutation saved as shape SaveResult queue then afterSave`): one request is in
flight, and each later send waits, in order, with the arguments it was made
with, until the reply before it has landed and its `then` has run. The source
sees one request at a time, `then` runs once per reply, and `pending(saved)`
stays true while anything waits. Assigning `saved = none` forgets nothing under
`queue`: every reply still lands. Keep newest-wins for a sign-in or a draft whose
late reply should be dropped (LLP 1092).

Independent writes a person may repeat before the first answers, such as two
renames or two comments, want every send at once. Declare the mutation
`parallel` (`mutation renamed as shape Renamed parallel refreshes issues`):
each send is asked when it is made, its write shows through the overlay until
its own reply and the answer asked after it, and its reply lands whatever else
is out. The slot and `failure(renamed)` follow the latest send that has
concluded, so a late reply never overwrites a newer outcome, and an earlier
send's failure shows unless a later send has already concluded. `pending`
stays true while any send is out, an assignment forgets no request, at most 64
sends are in flight, and there is no `then`. The source is called once per
send: one that reads local storage, changes it and writes it back must order
its own work, or the mutation should be `queue` (LLP 1161.000).

For a newest-wins mutation, the action that sends `saved` must not also
assign `saved = none`. Assignments commit after sends, so that reset can discard
the new reply even when it appears first. Hide a previous error while
`pending(saved)` instead. `none` means the slot contains no reply, not a failed write; use
`failure(saved)` for request failure and match the reply for a domain refusal.

A source sometimes needs changing context when deciding whether to refresh an
answer for the same logical entity. For example, a stored car status may need
the current minute to decide whether it must be fetched again:

```text
resource status = status(car) with minute as shape Status
```

The source receives `car`, then `minute`; changes to either ask again. `with`
accepts one or more expressions before `as shape`, and the call may be empty.
Call arguments identify the answer and should include its account or tenant.
Inputs after `with` are request context: they reach the source and trigger a new
request, but do not change persisted-answer identity. On hosts that persist
eligible store-reading answers, a returning launch can show the kept answer for
the same call arguments while the source is unready, even when a `with` input
changed. During a live replacement request, the prior displayed value may remain
visible even when call arguments changed, so private-data views must gate it by
owner and authorization. Neither call arguments nor `with` make a resource wait
for an upstream request to succeed. The default web JS target keeps no persisted
resource answers (LLP 1027.005 D5). Kept-answer diagnostics name a differing
argument and the state or resource it reads, never an identifying value.
The minute must already contain the current sample for the first ask; a timer
can update it thereafter. Use `refresh` or `refreshes` for values whose only job
is forcing another ask. Await true asynchronous prerequisites, such as a valid
session, inside the data source before issuing the dependent request.

Before an answer, a resource holds its baked value, its declared placeholder, or
its type's zero (`0`, `""`, `false`, `none`, `[]`, or a record of zeros):

```text
resource profile = loadProfile(id) as shape Profile else empty(name="Loading…")
resource profile = loadProfile(id) as shape Profile else previewProfile()
```

These are alternative declarations. `empty` supplies the type's zero, with named
constant field overrides for a record. A source-call placeholder takes plain-value
arguments, not state, and is answered once at build. See
[placeholder examples](https://github.com/expo/exact/blob/41ded8c5ede0b2959ef0daa83b1ff78545dd4428/contract/corpus/placeholder.contract);
[RealWorld](https://github.com/expo/exact/blob/41ded8c5ede0b2959ef0daa83b1ff78545dd4428/apps/realworld/app.contract) uses `else empty(…)`.

The app build bakes initial resource values into its plan for first paint. At
build there is no network, storage, store write or native module; a source that
needs a request is left unbaked and asked at run time. A baked value is only
the first frame: every host asks the TypeScript module again at launch (a native
host once the module loads after first pixel), even for a source with no
arguments, so what the module knows at launch reaches the view. `logs` names
each resource that showed a build-time answer and what its ask answered. Generate
the interface rather than guessing it:

```sh
cargo run -q -p contract -- types path/to/app.contract -o /tmp/app.contract.d.ts
cargo run -q -p contract -- rust path/to/app.contract -o /tmp/shapes.rs
```

Generated declarations are build artifacts. The data module's
`export const grants` governs network and storage permissions; a source name alone
grants nothing. The next section writes one end to end;
[Fieldnotes](https://github.com/expo/exact/blob/41ded8c5ede0b2959ef0daa83b1ff78545dd4428/apps/fieldnotes) is a larger storage example.
