lustre/server_component

Note: this is a release candidate for v4.0.0 and documentation is still a work in progress. If you spot an issue with docs or the library, or would like to get involved, please open an issue or a pull request.

Note: while Lustre v4 is in release candidate status, server components will not reliably work on Gleam’s JavaScript target. Until this message goes away, consider server components as being supported only on Erlang.

Functions

pub fn component(attrs: List(Attribute(a))) -> Element(a)

A simple wrapper to render a <lustre-server-component> element.

pub fn data(json: Json) -> Attribute(a)

Ocassionally you may want to attach custom data to an event sent to the server. This could be used to include a hash of the current build to detect if the event was sent from a stale client.


pub fn decode_action(
  dyn: Dynamic,
) -> Result(Action(a, ServerComponent), List(DecodeError))
pub fn emit(event: String, data: Json) -> Effect(a)
pub fn encode_patch(patch: Patch(a)) -> Json
pub fn include(properties: List(String)) -> Attribute(a)

Properties of the JavaScript event object are typically not serialisable. This means if we want to pass them to the server we need to copy them into a new object first.

This attribute tells Lustre what properties to include. Properties can come from nested objects by using dot notation. For example, you could include the id of the target element by passing ["target.id"].

import gleam/dynamic
import gleam/result.{try}
import lustre/element.{type Element}
import lustre/element/html
import lustre/event
import lustre/server

pub fn custom_button(on_click: fn(String) -> msg) -> Element(msg) {
  let handler = fn(event) {
    use target <- try(dynamic.field("target", dynamic.dynamic)(event))
    use id <- try(dynamic.field("id", dynamic.string)(target))

    Ok(on_click(id))
  }

  html.button([event.on_click(handler), server.include(["target.id"])], [
    element.text("Click me!")
  ])
}
pub fn route(path: String) -> Attribute(a)

The route attribute should always be included on a component to tell the client runtime what path to initiate the WebSocket connection on.

pub fn set_selector(sel: Selector(Action(a, b))) -> Effect(b)
pub fn subscribe(
  id: String,
  renderer: fn(Patch(a)) -> Nil,
) -> Action(a, ServerComponent)

A ServerComponent broadcasts patches to be applied to the DOM to any connected clients. This action is used to add a new client to a running server component.

pub fn unsubscribe(id: String) -> Action(a, ServerComponent)

Remove a registered renderer from a server component. If no renderer with the given id is found, this action has no effect.

Search Document