Datastar.Signals (DatastarEx v0.1.0)

View Source

Functions for reading and patching Datastar signals.

Signals represent client-side reactive state that can be synchronized between the server and browser.

Reading Signals

Signals can be read from GET requests (query parameters) or from the request body for other HTTP methods:

# Read signals into a map
signals = Datastar.Signals.read(conn)

# Read signals into a struct
{:ok, user_signals} = Datastar.Signals.read_as(conn, UserSignals)

Patching Signals

Send signal updates to the client:

sse
|> Datastar.Signals.patch(%{count: 42, message: "Hello"})

# Only patch if the signal doesn't exist on the client
sse
|> Datastar.Signals.patch(%{count: 42}, only_if_missing: true)

Summary

Functions

Patches signals on the client by sending an SSE event.

Patches signals only if they don't exist on the client.

Patches signals using a raw JSON string.

Reads signals from a Plug connection.

Reads signals from a connection and decodes them into a struct.

Functions

patch(sse, signals, opts \\ [])

@spec patch(Datastar.SSE.t(), map(), keyword()) :: Datastar.SSE.t()

Patches signals on the client by sending an SSE event.

Options

  • :only_if_missing - Only patch signals that don't exist on the client (default: false)
  • :event_id - Event ID for client tracking
  • :retry - Retry duration in milliseconds

Example

sse
|> Datastar.Signals.patch(%{count: 42})
|> Datastar.Signals.patch(%{message: "Hello"}, only_if_missing: true)

patch_if_missing(sse, signals, opts \\ [])

@spec patch_if_missing(Datastar.SSE.t(), map(), keyword()) :: Datastar.SSE.t()

Patches signals only if they don't exist on the client.

Convenience function equivalent to calling patch/3 with only_if_missing: true.

Example

sse
|> Datastar.Signals.patch_if_missing(%{count: 42})

patch_raw(sse, json, opts \\ [])

@spec patch_raw(Datastar.SSE.t(), String.t(), keyword()) :: Datastar.SSE.t()

Patches signals using a raw JSON string.

Example

sse
|> Datastar.Signals.patch_raw(~s({"count": 42}))

read(conn)

@spec read(Plug.Conn.t()) :: map()

Reads signals from a Plug connection.

For GET requests, reads from query parameters under the "datastar" key. For other methods, reads from the JSON request body.

Returns a map of signals or an empty map if no signals are present.

Example

signals = Datastar.Signals.read(conn)
# => %{"count" => 10, "message" => "Hello"}

read_as(conn, module)

@spec read_as(Plug.Conn.t(), module()) :: {:ok, struct()} | {:error, term()}

Reads signals from a connection and decodes them into a struct.

Example

defmodule UserSignals do
  defstruct [:name, :email, :count]
end

{:ok, signals} = Datastar.Signals.read_as(conn, UserSignals)