Current section
Files
Jump to
Current section
Files
guides/getting-started.md
# Getting started
Steps 1 to 5 follow one example: a product catalog where a table, a detail panel and a filter form share
a `catalog` store. Steps 6 to 8 add server actions, persistence and the offline queue.
Steps 4 and 5 continue in [Patch, invalidate and DOM bindings](patch-and-invalidate.md), step 6 in
[Server actions](server-actions.md), and steps 7 and 8 in [Persistence and the offline queue](persistence.md).
Read [Installation](../README.md#installation) first.
## 1. Create the store
Create stores before the LiveSocket connects, so the bridge and your hooks find them when they mount.
```js
// assets/js/app.js
import { createStore, LiveSliceHook, onBeforeElUpdated } from "live_slice";
createStore("catalog", {
state: { selectedId: null, filters: { query: "", inStock: false }, products: [] },
actions: {
// An action receives the current state and its arguments, and returns a
// partial state to merge, or undefined to change nothing.
select: (_state, id) => ({ selectedId: id }),
setFilters: (state, changes) => ({ filters: { ...state.filters, ...changes } }),
},
});
const liveSocket = new LiveSocket("/live", Socket, {
params: { _csrf_token: csrfToken },
hooks: { LiveSlice: LiveSliceHook, ProductDetail, FilterForm },
dom: { onBeforeElUpdated },
});
```
The bridge hook must be registered as `LiveSlice`. `onBeforeElUpdated` is optional (see
[step 5](patch-and-invalidate.md#5-dom-bindings)). If you already have a `dom.onBeforeElUpdated` callback, call `onBeforeElUpdated(fromEl, toEl)` from it.
## 2. Read and write the store from any hook
```js
import { getStore } from "live_slice";
export const ProductDetail = {
mounted() {
const store = getStore("catalog");
const render = () => {
const { selectedId, products } = store.getState();
const product = products.find(({ id }) => id === selectedId);
this.el.textContent = product ? `${product.name}: ${product.price}` : "Nothing selected";
};
render();
// Listeners run synchronously, and only when the selected value changes.
this.unsubscribers = [
store.subscribe((state) => state.selectedId, render),
store.subscribe((state) => state.products, render),
];
},
destroyed() {
for (const unsubscribe of this.unsubscribers) unsubscribe();
},
};
// Anywhere else, for example in a click handler:
getStore("catalog").actions.select(42);
```
The store API: `getState()`, `getInitialState()`, `setState(partial)`, `actions`, and
`subscribe(selector, listener, { equals })` or `subscribe(listener)` for the whole state. `listener` receives
`(next, previous)`; `equals` defaults to `Object.is`. `getConfirmedState()`, `getConfirmed(key)`,
`subscribeConfirmed(...)` and the `reducers` option read and derive the state without pending server actions;
see [The confirmed state](server-actions.md#the-confirmed-state). `getStore(name)` looks a store up and `resetStores()`
clears the registry (for tests) and returns a promise that resolves once persisted stores stopped writing.
`ensureStore(name, definition)` and `removeStore(name)` are for stores that come and go with an element; see
[Stores that come and go](tabs-and-connection.md#stores-that-come-and-go).
Server actions add `onRejected`, `onSettled` and `onConflict`, `maxResubmits`, `keepFailed` with `retry`,
`discard`, `onFailed` and `onRetry`, `cancel`, `resolveConflict`, `onQueued` (and the `id` and `queued` of each
call's promise), and a transport API used by the bridge (`pending()`, `confirm`, `reject`, `conflict`,
`onPending`, `recordAttempt`, `attempts`, `maxAttempts`, `exhausted`, `pushFailed`, `markQueued`,
`claimQueue`); see steps [6](server-actions.md) and [8](persistence.md#8-offline-queue),
[Failed pushes](persistence.md#failed-pushes), [Cancelling](persistence.md#cancelling) and
[Conflicts](conflicts.md). `connection`, `serverAt`, `onConnection` and the `connectionKeys` option tell how the
bridges reach the server (transport side: `setConnection`, `noteServerData`); see
[Connection state](tabs-and-connection.md#connection-state). Persistence
adds `ready`, `hydrated`, `flush()` and `onCleared`; see [step 7](persistence.md#7-persisted-state) and
[Multiple tabs](tabs-and-connection.md#multiple-tabs).
## 3. Bind the LiveView
```elixir
defmodule MyAppWeb.CatalogLive do
use MyAppWeb, :live_view
use LiveSlice, store: :catalog, mirror: [filters: [debounce: 300]]
def mount(_params, _session, socket) do
{:ok, assign(socket, rows: MyApp.Catalog.search(%{}))}
end
def render(assigns) do
~H"""
<LiveSlice.bridge id="catalog-store" module={__MODULE__} />
<form id="filters" phx-hook="FilterForm" phx-update="ignore">...</form>
<p id="detail" phx-hook="ProductDetail" phx-update="ignore"></p>
<table>
<tr
:for={row <- @rows}
id={"row-#{row.id}"}
data-store-match="catalog.selectedId"
data-store-value={row.id}
data-store-class="bg-blue-100 font-semibold"
>
<td>{row.name}</td>
</tr>
</table>
"""
end
# Receives each mirrored key as an atom, with the decoded JSON value.
@impl LiveSlice
def handle_store(:filters, %{"query" => query, "inStock" => in_stock}, socket)
when is_binary(query) and is_boolean(in_stock) do
filters = %{query: query, in_stock: in_stock}
{:noreply,
socket
|> assign(rows: MyApp.Catalog.search(filters))
|> LiveSlice.invalidate(:catalog, :products, url: ~p"/api/products?#{filters}")}
end
def handle_store(:filters, _invalid, socket), do: {:noreply, socket}
end
```
- `use LiveSlice` goes after `use Phoenix.LiveView` (here inside `use MyAppWeb, :live_view`), once per
LiveView. It attaches a hook that consumes `"live_slice:mirror"` and `"live_slice:action"` events before
your `handle_event/3`.
- `:mirror` lists the keys sent to the server: `[:selectedId, filters: [debounce: 300]]`. The debounce is
in milliseconds and defaults to `0`. Keys that are not listed never reach the server. A LiveView that
mirrors keys must define `handle_store/3`, which must return `{:noreply, socket}`. `flushMirror(store, key)`
(from `live_slice`) pushes a key at once instead of when its debounce elapses, for a step whose server side
needs the current value; see [Following the store](collaborative-keys.md#following-the-store).
- `handle_store/3` receives values sent by the browser: validate them like any other client input.
- `<LiveSlice.bridge id=... module={__MODULE__} />` renders the bridge element from the `use LiveSlice`
options of the LiveView that renders it, which is the one that receives its mirror events and server
actions. For another store whose patches, invalidates and DOM bindings the page uses, pass only
`store={:table}`: such a bridge mirrors nothing and sends no server actions, and passing `mirror` raises.