Livewire Rust Feature Lab

Feature lab

One page that mounts every capability of livewire·rust, in the order the guide lists them. This document is itself a page component; each section names the mechanism it proves, so the source can be read beside it.

01 · Typed state, actions, and parameters

Counter is a Rust struct. step is bound with wire:model; add(10) shows a typed action parameter; reset an action with none. The snapshot carries the fields, not the type.

Counter #Jduk8Ca0R1BRwJQs4Sl5

Count: 2 doubled: 4 step 1

Leave

Search:

page 0

Selection: 0

#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.counter")]
pub struct Counter {
    pub count: i32,
    pub step: i32,
    #[livewire(locked)]
    pub id: String,
}

#[livewire::component]
impl Counter {
    pub fn increment(&mut self) {
        self.count += self.step.max(1);
    }

    pub fn add(&mut self, by: i32) {
        self.count += by;
    }
}
#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.counter")]
pub struct Counter {
    pub count: i32,
    pub step: i32,
    #[livewire(locked)]
    pub id: String,
}

#[livewire::component]
impl Counter {
    pub fn increment(&mut self) {
        self.count += self.step.max(1);
    }

    pub fn add(&mut self, by: i32) {
        self.count += by;
    }
}

02 · Validation and errors

label declares validate(required, max_length(10)); pressing Save the label runs the rules and renders the message beside the field. A form object fails the same way: Profile records an error for preferences.name.

Profile

The form object crosses the wire as one object; the browser updates it by path.

#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.profile")]
pub struct Profile {
    #[livewire(form)]
    pub preferences: Preferences,
}

#[component]
impl Profile {
    pub fn reject(&mut self, context: &mut ComponentContext) {
        context.add_error("preferences.name", "The name is taken.");
    }
}

// In the counter, a declared rule runs on the save action:
#[livewire(validate(required, max_length(10)))]
pub label: String,

// and the view reads the message back:
{% if error("label") %}{{ error("label") }}{% endif %}
#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.profile")]
pub struct Profile {
    #[livewire(form)]
    pub preferences: Preferences,
}

#[component]
impl Profile {
    pub fn reject(&mut self, context: &mut ComponentContext) {
        context.add_error("preferences.name", "The name is taken.");
    }
}

// In the counter, a declared rule runs on the save action:
#[livewire(validate(required, max_length(10)))]
pub label: String,

// and the view reads the message back:
{% if error("label") %}{{ error("label") }}{% endif %}

03 · URL, session, and locked state

In the counter above: search is the page's ?q= (replace), page is ?page= (push, always shown), selection lives in the session and survives a reload, and the id is locked — the browser may read it and never write it.

// The page's own query string, and what survives a reload.
#[livewire(url(as = "q", use = "replace"))]
pub search: String,

#[livewire(url(as = "page", use = "push", always_show = true, except = "keep"))]
pub page: i64,

#[livewire(session(key = "counter-selection"))]
pub selection: i64,

// The browser may read it, never write it.
#[livewire(locked)]
pub id: String,
// The page's own query string, and what survives a reload.
#[livewire(url(as = "q", use = "replace"))]
pub search: String,

#[livewire(url(as = "page", use = "push", always_show = true, except = "keep"))]
pub page: i64,

#[livewire(session(key = "counter-selection"))]
pub selection: i64,

// The browser may read it, never write it.
#[livewire(locked)]
pub id: String,

04 · Events and JavaScript

Announce dispatches counter-announced; the Alpine listener in the counter's own view reveals the banner. Celebrate evaluates an xjs statement, and window.__counterCelebrated holds the count afterwards.

/// The page may dispatch this event; the component listens.
#[livewire(on = "counter-reset")]
pub fn reset_from_event(&mut self) {
    self.count = 0;
}

/// Tells the page the new count.
pub fn announce(&mut self, context: &mut ComponentContext) {
    context.push_effect(
        "dispatches",
        json!({"name": "counter-announced", "params": {"count": self.count}}),
    );
}

/// Runs a statement in the browser once the answer morphed.
pub fn celebrate(&mut self, context: &mut ComponentContext) {
    context.xjs(format!("window.__counterCelebrated = {}", self.count));
}
/// The page may dispatch this event; the component listens.
#[livewire(on = "counter-reset")]
pub fn reset_from_event(&mut self) {
    self.count = 0;
}

/// Tells the page the new count.
pub fn announce(&mut self, context: &mut ComponentContext) {
    context.push_effect(
        "dispatches",
        json!({"name": "counter-announced", "params": {"count": self.count}}),
    );
}

/// Runs a statement in the browser once the answer morphed.
pub fn celebrate(&mut self, context: &mut ComponentContext) {
    context.xjs(format!("window.__counterCelebrated = {}", self.count));
}

05 · Effects besides markup

One component, six answers: new markup, a JSON return the browser reads, a call sent ahead of the batch, a renderless call, an awaited body, and an evaluated statement.

Effects

Every action below starts from the same click path and answers differently: new markup, a JSON value, a call sent ahead of the batch, a call that changes state without rendering, an awaited body, and a statement evaluated in the browser.

Count 1 · silent actions ran 0 times

no report yet
/// Answers with JSON: `$wire.report()` resolves to this value.
#[livewire(json)]
pub fn report(&mut self) -> serde_json::Value {
    json!({"count": self.count, "doubled": self.count * 2})
}

/// Changes state and sends a snapshot, but no markup.
#[livewire(renderless)]
pub fn quietly(&mut self) {
    self.fired += 1;
}

/// The browser sends this call ahead of the others.
#[livewire(async)]
pub fn refresh_later(&mut self) {
    self.fired += 1;
}

/// An async body the runtime awaits before it renders.
pub async fn slow(&mut self) {
    self.count += 10;
}
/// Answers with JSON: `$wire.report()` resolves to this value.
#[livewire(json)]
pub fn report(&mut self) -> serde_json::Value {
    json!({"count": self.count, "doubled": self.count * 2})
}

/// Changes state and sends a snapshot, but no markup.
#[livewire(renderless)]
pub fn quietly(&mut self) {
    self.fired += 1;
}

/// The browser sends this call ahead of the others.
#[livewire(async)]
pub fn refresh_later(&mut self) {
    self.fired += 1;
}

/// An async body the runtime awaits before it renders.
pub async fn slow(&mut self) {
    self.count += 10;
}

06 · Nesting, reactive props, and slots

The parent passes :step down; the child compares it and answers {skip:true} when it did not change. The slot is the child's fragment of the parent's markup, and it survives the child's own renders.

Reactive parent

The parent passes step down; an unchanged child skips its own render.

Nested child

Step: 0

from the parent
<!-- nested-wrapper.livewire -->
<button type="button" wire:click="bump" data-bump>Bump</button>

<livewire:nested-child :step="step" wire:key="nested-child-1">
    <em data-slot-content>from the parent</em>
</livewire:nested-child>

<!-- nested-child.livewire -->
<p>Step: <strong data-child-step>{{ step }}</strong></p>
<div data-slot>{{ slot }}</div>
<!-- nested-wrapper.livewire -->
<button type="button" wire:click="bump" data-bump>Bump</button>

<livewire:nested-child :step="step" wire:key="nested-child-1">
    <em data-slot-content>from the parent</em>
</livewire:nested-child>

<!-- nested-child.livewire -->
<p>Step: <strong data-child-step>{{ step }}</strong></p>
<div data-slot>{{ slot }}</div>

07 · Lazy and deferred

The first render is a placeholder carrying wire:init="__lazyLoad"; the request it makes renders the component's own view.

#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.deferred")]
pub struct Deferred {
    pub title: String,
}

// The first render is a placeholder; the browser's `wire:init` renders the view.
#[component(lazy)]
impl Deferred {}
#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.deferred")]
pub struct Deferred {
    pub title: String,
}

// The first render is a placeholder; the browser's `wire:init` renders the view.
#[component(lazy)]
impl Deferred {}

08 · Islands

The count lives inside an @island; an action on it answers with islandFragments and the rest of the component's markup is left alone.

Ticker

0

<div class="card">
    <h2>Ticker</h2>

    @island(name: 'log')
        <p data-count>{{ count }}</p>
        <button type="button" wire:click="tick" data-tick>Tick</button>
    @endisland
</div>

// An action from inside the island answers with `islandFragments`,
// and the rest of the component's markup stays where it is.
<div class="card">
    <h2>Ticker</h2>

    @island(name: 'log')
        <p data-count>{{ count }}</p>
        <button type="button" wire:click="tick" data-tick>Tick</button>
    @endisland
</div>

// An action from inside the island answers with `islandFragments`,
// and the rest of the component's markup stays where it is.

09 · Teleport and persist

One element mounts on the document body instead of the card; another is kept across updates by the client.

Teleport and persist

The dialog leaves this card and mounts on the document body; the second input survives re-renders because the client is told to keep its element.

Persisted element: x-persist keeps this input across updates.

Sent: · kept:

{% if open %}
    @teleport('body')
        <div data-teleport-dialog>
            <input type="text" wire:model.live="draft">
            <button type="button" wire:click="send">Send</button>
        </div>
    @endteleport
{% endif %}

@persist('lab-kept')
    <input type="text" wire:model.live="kept">
@endpersist
{% if open %}
    @teleport('body')
        <div data-teleport-dialog>
            <input type="text" wire:model.live="draft">
            <button type="button" wire:click="send">Send</button>
        </div>
    @endteleport
{% endif %}

@persist('lab-kept')
    <input type="text" wire:model.live="kept">
@endpersist

10 · Model references

The field holds a ModelRef<Post>: the snapshot carries the key, and the pipeline fetches the row before the response renders. Press Load the first post.

Post card

No post loaded.

#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.post-card")]
pub struct PostCard {
    #[livewire(model)]
    pub post: ModelRef<Post>,
}

#[component]
impl PostCard {
    /// The snapshot keeps the key; the pipeline fetches the row before the answer renders.
    pub fn load(&mut self, id: i64) {
        self.post = ModelRef::referencing(id);
    }
}
#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.post-card")]
pub struct PostCard {
    #[livewire(model)]
    pub post: ModelRef<Post>,
}

#[component]
impl PostCard {
    /// The snapshot keeps the key; the pipeline fetches the row before the answer renders.
    pub fn load(&mut self, id: i64) {
        self.post = ModelRef::referencing(id);
    }
}

11 · Pagination

The paginator is the framework's, and the page number lives in the URL. The list is a page of its own because it needs the database before it renders: the paginated list.

#[livewire(url(as = "page", use = "push", always_show = true))]
pub page: i64,

pub async fn next(&mut self) {
    self.go(self.page + 1).await;
}

async fn load(&mut self) -> Result<()> {
    let paginator = Post::query()
        .order_by(Post::id.desc())
        .paginate(PER_PAGE)
        .page(self.page as u64)
        .await?;

    self.posts = paginator.items().iter().map(Row::from).collect();
    Ok(())
}
#[livewire(url(as = "page", use = "push", always_show = true))]
pub page: i64,

pub async fn next(&mut self) {
    self.go(self.page + 1).await;
}

async fn load(&mut self) -> Result<()> {
    let paginator = Post::query()
        .order_by(Post::id.desc())
        .paginate(PER_PAGE)
        .page(self.page as u64)
        .await?;

    self.posts = paginator.items().iter().map(Row::from).collect();
    Ok(())
}

12 · Uploads

A signed URL, a file stored on the temporary disk, a preview limited by extension, and a field that carries only the file's name.

Upload a file

The browser asks for a signed URL, posts the file there, and names the temporary file back.

<input type="file" wire:model="photo" data-file>

<!-- The browser asks for a signed URL, posts the file there, then
     names the temporary file back; the field holds only the name. -->
<p data-photo>{{ photo }}</p>

{% if errors.photo is defined %}
    <p data-error>{{ errors.photo }}</p>
{% endif %}
<input type="file" wire:model="photo" data-file>

<!-- The browser asks for a signed URL, posts the file there, then
     names the temporary file back; the field holds only the name. -->
<p data-photo>{{ photo }}</p>

{% if errors.photo is defined %}
    <p data-error>{{ errors.photo }}</p>
{% endif %}

13 · Streaming

The action writes frames as it works; they arrive before the final payload, and the client appends each one to its wire:stream target.

Streamed response

The action writes three frames before the response's own payload.

#[component]
impl Streamer {
    /// Writes lines into the element marked `wire:stream="log"`.
    pub fn run(&mut self, context: &mut ComponentContext) {
        for line in ["one", "two", "three"] {
            // The frame shows the line as the action runs; the field keeps it,
            // because the response's own markup replaces what the frames appended.
            context.stream("log", format!("<div data-line>{line}</div>"));
            self.lines.push(line.to_owned());
        }
    }
}
#[component]
impl Streamer {
    /// Writes lines into the element marked `wire:stream="log"`.
    pub fn run(&mut self, context: &mut ComponentContext) {
        for line in ["one", "two", "three"] {
            // The frame shows the line as the action runs; the field keeps it,
            // because the response's own markup replaces what the frames appended.
            context.stream("log", format!("<div data-line>{line}</div>"));
            self.lines.push(line.to_owned());
        }
    }
}

14 · Scripts and assets run once per type

Two counters of the same type share one @script and one @assets run. window.__counterScripts counts the runs, and it stays at one.

Counter #b32haajzDI8RfpugKAGz

Count: 10 doubled: 20 step 1

Leave

Search:

page 0

Selection: 0

Counter #uFryH37SSGc7ExzbKRHR

Count: 20 doubled: 40 step 1

Leave

Search:

page 0

Selection: 0

<!-- One run per component type, however many instances the page mounts. -->
@script
    <script>window.__labScripts = (window.__labScripts || 0) + 1;</script>
@endscript

@assets
    <script>window.__labAssets = (window.__labAssets || 0) + 1;</script>
@endassets
<!-- One run per component type, however many instances the page mounts. -->
@script
    <script>window.__labScripts = (window.__labScripts || 0) + 1;</script>
@endscript

@assets
    <script>window.__labAssets = (window.__labAssets || 0) + 1;</script>
@endassets

15 · Pages, guards, downloads, redirects

This document is a page component. Two more prove the edges around it: a page component of its own, and a guarded page whose registered PersistentMiddleware refuses updates when the request carries x-paused. In the counter, Export answers with a download and Leave with a redirect.

Authorization is a policy on the action, #[livewire(authorize(..))], which answers 403; the lab keeps that off a button because the client answers a refusal with its own error dialog, and the tests assert the status instead.

// src/http/handlers/page.rs — the component's own view is the document.
pub async fn lab(registry: Inject<Arc<ComponentRegistry>>) -> Response {
    let html = livewire::page::render_page(&registry, "lab-page", Params::default())
        .expect("the lab page renders");

    Response::new(Html::raw(html))
}

// src/livewire/guard.rs — a guard runs on every update of the page it names.
#[livewire::__private::async_trait]
impl PersistentMiddleware for PausedUpdates {
    async fn handle(&self, request: &Request, page: &PageContext) -> Option<Response> {
        if request.header("x-paused").is_some() && page.path == "/livewire/streamer" {
            return Some(Response::new("Paused").with_status(StatusCode::SERVICE_UNAVAILABLE));
        }

        None
    }
}
// src/http/handlers/page.rs — the component's own view is the document.
pub async fn lab(registry: Inject<Arc<ComponentRegistry>>) -> Response {
    let html = livewire::page::render_page(&registry, "lab-page", Params::default())
        .expect("the lab page renders");

    Response::new(Html::raw(html))
}

// src/livewire/guard.rs — a guard runs on every update of the page it names.
#[livewire::__private::async_trait]
impl PersistentMiddleware for PausedUpdates {
    async fn handle(&self, request: &Request, page: &PageContext) -> Option<Response> {
        if request.header("x-paused").is_some() && page.path == "/livewire/streamer" {
            return Some(Response::new("Paused").with_status(StatusCode::SERVICE_UNAVAILABLE));
        }

        None
    }
}