# Server actions

Step 6 of the walkthrough that starts in [Getting started](getting-started.md), and the confirmed state: the
state without the server actions still pending.

## 6. Optimistic server actions

An action written as `{ apply, server }` changes the store at once and is sent to the LiveView, which
accepts or refuses it. A refused action is rolled back.

```js
const cart = createStore("cart", {
  state: { items: [], count: 0, note: "" },
  actions: {
    addItem: {
      // Applied at once, and again whenever the state under it changes, so keep it pure.
      apply: (state, sku) => ({ items: [...state.items, sku], count: state.count + 1 }),
      // The action name declared in `use LiveSlice, actions: [...]`.
      server: "add_item",
    },
    // A plain function stays a client-only action.
    clearNote: () => ({ note: "" }),
  },
});

cart.onRejected(({ action, args, reason }) => showError(`${action}(${args}) failed: ${reason}`));

cart.actions.addItem("tea"); // items is ["tea"] at once; the returned promise can be ignored
await cart.actions.addItem("milk"); // resolves when accepted, rejects with the reason when refused
```

```elixir
defmodule MyAppWeb.CartLive do
  use MyAppWeb, :live_view
  use LiveSlice, store: :cart, actions: [:add_item]

  @impl LiveSlice
  def handle_action(:add_item, [sku], %{id: mutation_id}, socket) when is_binary(sku) do
    case MyApp.Carts.add_item(socket.assigns.cart, sku, mutation_id) do
      # Accept and keep the client's change: {:ok, socket}.
      # Accept and merge the server's view over the client state (the server wins):
      {:ok, cart} -> {:ok, %{items: cart.items, count: length(cart.items)}, assign(socket, cart: cart)}
      # Refuse: the client rolls the change back. The reason must be JSON-encodable.
      {:error, :out_of_stock} -> {:error, "out_of_stock", socket}
    end
  end
end
```

- The store keeps a confirmed state and the pending actions in call order. `getState()` is the confirmed
  state with every pending `apply` replayed on top. Accepting folds the action into the confirmed state;
  refusing drops it and replays the others, so later pending actions stay applied.
- `setState`, client-only actions, `patch` and `invalidate` write the confirmed state, and pending actions
  are replayed on top. For a key that a pending action also writes, the replayed value stays visible until
  the action settles, so keep keys owned by server actions apart from client-only keys.
- `apply` is optional; without it nothing changes until the server answers. An `apply` that throws when the
  action is called throws to the caller. One that throws while being replayed rejects that action.
- Arguments are sent as JSON. `handle_action/4` receives them as a list, with `meta.id`, a client-generated
  UUID that stays the same if the call is sent again, and `meta.base` for an action that declares the
  version it is based on (see [Conflicts](conflicts.md)). Undeclared actions are refused with
  `"unknown_action"` and never become atoms. A `handle_action/4` that raises crashes the LiveView, like
  any other callback.
- The reply is sent as JSON after the handler ran. A returned state that is a struct or cannot be encoded
  is left out (the call is still accepted, with the client's optimistic state), and a reason that cannot
  be encoded, such as a tuple or a changeset, becomes `"invalid_reason"`; both are logged with
  `Logger.error`. Return a plain map of JSON values as state and a string or map as reason.
- `{:conflict, state, socket}` and `{:conflict, state, reason, socket}` refuse a call made on data that changed
  since; see [Conflicts](conflicts.md).
- The bridge pushes pending actions as `live_slice:action`, one at a time and in call order, and keeps
  them while the LiveView is disconnected; see [step 8](persistence.md#8-offline-queue). Only a bridge rendered
  with `module={__MODULE__}`
  for a LiveView that declares `:actions` sends them (it carries a `data-actions` marker). If two
  LiveViews on one page declare actions for the same store, the first bridge sends them and the second
  logs an error and waits until the first is destroyed.

## The confirmed state

`getState()` is what the user sees: the confirmed state with the pending actions applied. The confirmed state
alone is public too:

```js
store.getConfirmedState(); // what the server confirmed or sent, plus setState and client-only actions
store.getConfirmed("changes"); // one key of it
store.subscribeConfirmed((state) => state.changes, (next, previous) => save(next)); // like subscribe
```

`subscribeConfirmed(selector, listener, { equals })` (or `subscribeConfirmed(listener)`) is called when the
confirmed state changes: a patch, an invalidate, `setState`, a client-only action, an accepted or conflicting
server action, hydration. It is never called for a pending action applied or rolled back, and its listeners run
before those of `subscribe`.

**Deriving a key from a key the server writes.** A patch replaces a key whole, so a server that sends one
change at a time often patches a small delta key that the client folds into a larger one. A `subscribe` that
reads `getState()` and writes the fold with `setState` writes the optimistic values of pending actions into the
confirmed state with it: a refused action then stays visible. Fold on the confirmed state instead, with
`reducers`:

```js
createStore("assets", {
  state: { changes: {}, latestChanges: null },
  actions: {
    // Writes `changes` optimistically: no separate key for local changes.
    inspect: { apply: (state, id) => ({ changes: { ...state.changes, [id]: { status: "ok" } } }), server: "inspect" },
  },
  // Called whenever `latestChanges` is written to the confirmed state, by a patch or a reply.
  reducers: { latestChanges: (confirmed, latest) => ({ changes: { ...confirmed.changes, ...latest } }) },
});
```

- `reducers[key](confirmedState, value)` runs after every write of `key` to the confirmed state (`setState`,
  and so patches and invalidates, client-only actions, and the `state` of a reply or a conflict), with the
  confirmed state that already holds the new value. It returns a partial state that is merged in the same write
  (subscribers are called once), or `null`/`undefined` for nothing. The pending actions are then replayed on
  top, so an action may write the folded key optimistically, and its rollback leaves exactly what the reducers
  folded.
- A reducer that throws is reported with `console.error` and skipped; the write itself is kept. Reducers do not
  run on hydration (persist the folded key: it was reduced already) nor on the keys a reducer returns.
- The same fold written as `subscribeConfirmed` plus `setState({ changes: fold(store.getConfirmed("changes"),
  latest) })` is also correct, in two writes. For entries of one key the server can also patch the entries
  themselves; see [Patching entries](patch-and-invalidate.md#patching-entries).
- A fold sees every value only if every value reaches the client: a LiveView that coalesces its patches must name
  the delta key in `keep` (see [Coalescing patches](patch-and-invalidate.md#coalescing-patches)), or two deltas sent close together
  collapse into the last one. Entry operations (`put_entries` into `changes` itself) need no fold and no `keep`.
