How stores behave across tabs, reconnects and live navigation, how they report their connection, and stores created and removed with an element.
Multiple tabs
Every tab of an origin that creates a persisted store with the same name shares one stored record. Writes never replace it blindly; each one is an atomic read-modify-write (one IndexedDB transaction with the default storage):
- Queued actions are merged by id: a write keeps the actions other tabs queued, removes the ones this tab settled, and appends this tab's new ones. The queue is ordered by when each action first reached the record, and within a tab by call order. Attempt counts only grow.
- Persisted keys are merged per key, last write wins: a tab writes only the keys it changed since it last
wrote or restored them. A record with another
versiongets the writing tab's whole state and version (its queue is still merged).
Where the browser has Web Locks and
BroadcastChannel, the tabs also coordinate,
through a lock and a channel both named live_slice:<store name>:
- One tab at a time sends the queue: the bridge claims the lock while it is connected (
claimQueue) and gives it up when it disconnects or is destroyed. Other tabs keep their actions queued and persisted. - After each write, a tab announces it on the channel; the tab holding the lock then adopts the actions
other tabs queued (and announces them through
onPending) and sends them. - Every settled action is announced too, with the server's state or the rejection reason, so the tab that
called it settles it as well: its promise resolves or rejects and its
onSettledandonRejectedlisteners fire there.
Persisted keys are shared live (persist: { share: true }, the default): after each write, the tab
announces the values it wrote, and the other tabs show them at once, without writing them back. Each write
of the record counts up (seq, kept in the record with a stamp per key, past every stamp the writing tab
knows and at least the current time in milliseconds), and a tab takes an announced value only when its stamp
is newer than the value it holds, so tabs that hear announcements in different orders end on the value the
record holds, also when a newer value is announced while the tab's own write is still completing. A key a tab
changed and has not written yet keeps its value there; its write (100 ms later at most) then wins and is
announced in turn. A tab still running an older version of the library after a deploy rewrites the record
without seq and stamps; the next write of a current tab still counts past what the others hold. This is a
changed default: before, a tab kept showing an old value until it reloaded, and could write it back over
another tab's newer decision when it changed the key itself (a filter object edited in two tabs). persist: { share: false } turns it
off; persist: { share: ["filters"] } shares only the keys listed (the others are still persisted, and a reload
restores the last value any tab wrote). Mirrored keys are pushed to each tab's own LiveView as any change is;
collaborative keys are never persisted and keep their own channel.
removeStore(name, { clearPersisted: true }) is announced too: the other tabs stop writing the record (so
they do not bring it back), give up their queue claim, put their persisted keys back to the store's initial
values and call store.onCleared(listener). Their pending server actions stay in memory, applied and sent by
their own bridge as before, but are no longer stored, so a reload does not bring them back; an application
that wants them gone cancels or discards them in onCleared. The record is not deleted but replaced by a
marker of the clear ({cleared: id}, no state and no queue), which every write checks inside its atomic
update: a write another tab started before it heard of the clear finds the marker, writes nothing and clears
that tab as the announcement would. A store created afterwards (in any tab, or in the same tab right after the
removal) starts from the marker, empty, and persists as usual. With a storage without update (a get then a
set), a write can still slip between the two.
Tabs share the queue and their persisted keys, not the rest of their state: a tab shows its own changes (and
what it restored on load) until the server's replies or patches reach it. Without Web Locks or
BroadcastChannel, or with
persist: { locks: null } or persist: { BroadcastChannel: null }, every tab sends the actions it holds,
and writes are still merged as above. An action restored by a reload while the tab that called it is still
open can then be sent by both tabs; delivery is at least once anyway, so idempotent handlers cope with it.
persist.locks and persist.BroadcastChannel also accept other implementations, for tests.
Mount, reconnect and live navigation
- The bridge assumes the LiveView mounted with the store's initial values, so create the store with the same defaults the LiveView renders. Mirrored keys that already differ from the initial state when the bridge mounts are pushed at once. Stores live in the page's JavaScript and outlive a live navigation, so this happens when a LiveView mounts on top of state changed on an earlier page.
- While disconnected or offline, the bridge pushes nothing. On
reconnected(), every mirrored key is pushed at once (or as soon as the browser is back online), without the debounce, since the server process is new; then the queued server actions follow. - Values that came from the server through
patchorinvalidateare not pushed back.
Connection state
Each store knows how its bridges reach the server and when it last got data from it:
store.connection; // "connected", "connecting", "reconnecting", "offline" or "detached"
store.serverAt; // when this page last received server data for the store (ms), or null
store.onConnection(({ status, serverAt }) => render(status, serverAt));
// Or as keys of the store, to render and bind like any other key:
createStore("dashboard", {
state: { districts: {} },
connectionKeys: { status: "connection", serverAt: "dataAt" },
// optional: "as of" survives a reload offline; kept out of `share`, so another tab's time does not show here
persist: { keys: ["districts", "dataAt"], share: ["districts"] },
});| Status | When |
|---|---|
"connected" | A bridge of the store is mounted, its LiveView is joined and the browser reports a network. |
"reconnecting" | The LiveView was lost (disconnected()) and the browser reports a network. |
"connecting" | A bridge of the store is expected and not mounted yet: the page holds its element (from the end of the render that put it there, before LiveView mounts that render's hooks), or a live navigation destroyed the store's last bridge and LiveView is loading the next page. Or one was mounted offline (see The offline mount) and its LiveView has not joined. |
"offline" | The browser reports no network (navigator.onLine is false). |
"detached" | No bridge of the store is mounted and none is expected: nothing on this page will connect the store, whatever the network. |
Without a bridge mounted, the store tells "trying to connect" from "nothing here will connect" by the page's bridge
elements (<LiveSlice.bridge> renders <div phx-hook="LiveSlice" data-store="...">):
A new store starts
"detached"when the page's document holds no bridge element for it, and"connecting"when it holds one that LiveView has not mounted yet (it mounts the hook once its LiveView joined). The element is in the server-rendered HTML, so a page that has a bridge never shows"detached"while it loads, offline or with a server that does not answer included. Once LiveView loaded the page (phx:page-loading-stopof kind"initial", after the main LiveView's hooks mounted), a store still without a bridge and without an element waiting (the connected render left it out) becomes"detached". A store created while the document is still being parsed starts"connecting"and is decided atDOMContentLoaded. Without a document (a worker, tests under Node) it starts"connecting", as before.A bridge mounts: the statuses above, from the best of the store's mounted bridges.
The last bridge is destroyed by a render that removed its element:
"detached"at once, unless another bridge element of the store waits to mount ("connecting").A live navigation destroys the hooks of the page it leaves while that page is still shown, before the next page joined: the store is
"connecting"meanwhile. Once LiveView loaded the next page (phx:page-loading-stopof kind"initial", after the main LiveView's hooks mounted), it is the status of the bridge that page mounted, or"detached"when it mounted none and holds none that waits. A navigation between two pages that both render the bridge goes"connected","connecting","connected". A store"detached"on the page left stays so while the next page loads, and turns"connecting"with the render that brings in a page holding its bridge (next item):"detached","connecting","connected"; toward a page without it, it stays"detached"throughout.A render puts a bridge element in the page (the join patch of a live navigation's next page, a live patch, a render after an event, a nested LiveView's join): a
"detached"store becomes"connecting"once the render's elements are in the page and before any of its hooks mounts. LiveView dispatchesphx:updateon the document at the end of a patch, then mounts the hooks of the elements the patch added, in page order; the bridge turns the store"connecting"onphx:update. A hook placed before the bridge in the page therefore reads"connecting", as on a page that held the element when it loaded: the bridge element does not have to come first. The store then takes the bridge's status when the bridge mounts; if none of its bridges mounted by the time LiveView loaded a page (phx:page-loading-stopof kind"initial") and no element waits, it is"detached"again."detached"still shows before such a render: a bridge inside a nested LiveView (live_render) reached by live navigation comes with that LiveView's join patch, which LiveView applies after its parent's hooks mounted and after it reported the page loaded, so the parent's hooks can read"detached".A bridge whose store was removed is "detached" from that store (see Stores that come and go): it reports nothing to a store created again under the name, which is
"detached"too unless a bridge element waits for it.The bridge follows both the LiveView's callbacks and the browser's
onlineandofflineevents. A short loss of network often leaves the socket open, so nodisconnected()orreconnected()comes: theofflineevent makes the store"offline", and theonlineevent makes it"connected"again.With several bridges for one store on a page, the best status counts (connected, then reconnecting, connecting, offline).
"detached"only applies while none is mounted.serverAtmoves on every patch, invalidate result, reply to a server action and collaborative-key message of the store, andonConnectionis called each time. A store removed withremoveStoregets nothing from the bridges mounted on it.connectionKeys: { status, serverAt }(either may be left out) writes the same into those keys of the confirmed state: the status key starts as the store's first status ("connecting"or"detached", above) and the time key asnull, andonConnectionis called on every change. Do not persist the status key. Persisting the time key keeps "data as of" across a reload, but persisted keys are shared live between tabs by default, and the time is this tab's: leave it out ofpersist.share(a list of the keys to share, as above), or do not persist it. A key written there is a normal key:subscribe, DOM bindings (data-store-match="dashboard.connection") and mirrors see it.Transports report through
store.setConnection(status)andstore.noteServerData(at?); a transport of its own may report"detached"too.
Stores that come and go
Stores are global by name and createStore throws on a name that is taken, which suits stores created once
in app.js. A store that belongs to an element that mounts and unmounts, such as one store per map, is
created and removed by that element's hook instead:
import { ensureStore, removeStore } from "live_slice";
export const PlacesMap = {
mounted() {
// Returns the store named "map:places" if it exists, or creates it with this definition.
this.store = ensureStore("map:places", { state: { selectedId: null, viewport: null } });
},
destroyed() {
removeStore("map:places");
},
};ensureStore(name, definition)returns the store registered undername, or creates it withdefinition(the options ofcreateStore). The definition of an existing store is not applied again.removeStore(name, { clearPersisted })removes that one store, asresetStores()does for all of them: a persisted store stops writing (a write still scheduled or queued is dropped;await store.flush()first to keep it), stops talking to other tabs and gives up its queue claim. It also drops the store's subscribers andonPending,onRejectedandonSettledlisteners. It returns a promise that resolves once the storage call in flight finished. The stored record is kept, so a store created again under the name restores it, pending server actions included; withclearPersisted: truethe record is replaced by a marker of the clear ({cleared: id}, nothing of the state or the queue) once the call in flight finished (for every tab of the origin, which share it), and the other tabs are told (see Multiple tabs). Pending server actions of a removed store stay pending. A store created again under the name (the sign-in page after a sign-out) restores nothing from the marker and leaves it in place until a persisted key or its queue changes; it then writes a record of the clear'sepoch, which tabs that still hold the cleared state do not write over.- A store can be created again under the name right away. It is a new store: a bridge mounted on the removed one is detached from then on (it pushes nothing, applies no patch or invalidate and stops updating DOM bindings) and only a bridge mounted afterwards follows the new store. So render the bridge for such a store next to the element whose hook creates it, after it in the document: LiveView mounts hooks in document order, so the store exists when the bridge mounts, and both go together.