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, step 6 in Server actions, and steps 7 and 8 in Persistence and the offline queue. Read Installation first.
1. Create the store
Create stores before the LiveSocket connects, so the bridge and your hooks find them when they mount.
// 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). If you already have a dom.onBeforeElUpdated callback, call onBeforeElUpdated(fromEl, toEl) from it.
2. Read and write the store from any hook
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. 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.
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 and 8,
Failed pushes, Cancelling and
Conflicts. connection, serverAt, onConnection and the connectionKeys option tell how the
bridges reach the server (transport side: setConnection, noteServerData); see
Connection state. Persistence
adds ready, hydrated, flush() and onCleared; see step 7 and
Multiple tabs.
3. Bind the LiveView
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}
enduse LiveSlicegoes afteruse Phoenix.LiveView(here insideuse MyAppWeb, :live_view), once per LiveView. It attaches a hook that consumes"live_slice:mirror"and"live_slice:action"events before yourhandle_event/3.:mirrorlists the keys sent to the server:[:selectedId, filters: [debounce: 300]]. The debounce is in milliseconds and defaults to0. Keys that are not listed never reach the server. A LiveView that mirrors keys must definehandle_store/3, which must return{:noreply, socket}.flushMirror(store, key)(fromlive_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.handle_store/3receives values sent by the browser: validate them like any other client input.<LiveSlice.bridge id=... module={__MODULE__} />renders the bridge element from theuse LiveSliceoptions 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 onlystore={:table}: such a bridge mirrors nothing and sends no server actions, and passingmirrorraises.