### POST /endpoint with Options Example
Source: https://data-star.dev/docs
Example of using @get action with various options.
```APIDOC
## Example Request with Options
```html
```
```
--------------------------------
### Configure Datastar Action Options
Source: https://data-star.dev/docs
This example demonstrates how to configure various options for a Datastar action, including filtering signals, setting custom headers, enabling open-when-hidden, and disabling request cancellation. It shows a button triggering a GET request with these configurations.
```html
```
--------------------------------
### JavaScript SSE Event Handling Setup
Source: https://data-star.dev/docs
This JavaScript snippet shows the initial setup for creating a `ServerSentEventGenerator` instance, which also sends the necessary headers for SSE. It's the starting point for sending SSE events from a server.
```javascript
// Creates a new `ServerSentEventGenerator` instance (this also sends required headers)
ServerSentEventGenerator.stream(req, res, (stream) => {
```
--------------------------------
### C# SDK for Patch Signals
Source: https://data-star.dev/docs
Example using the Datastar C# SDK to add Datastar as a service and patch signals asynchronously. It demonstrates patching signals with a delay between updates.
```csharp
1using StarFederation.Datastar.DependencyInjection;
2
3// Adds Datastar as a service
4builder.Services.AddDatastar();
5
6app.MapGet("/hal", async (IDatastarService datastarService) =>
7{
8 // Patches signals.
9 await datastarService.PatchSignalsAsync(new { hal = "Affirmative, Dave. I read you" });
10
11 await Task.Delay(TimeSpan.FromSeconds(3));
12
13 await datastarService.PatchSignalsAsync(new { hal = "..." });
14});
```
--------------------------------
### Reading Signals in Ruby
Source: https://data-star.dev/docs
An example of setting up and reading signals in Ruby using the Datastar library. It initializes Datastar with the request and response objects and then accesses signals via `datastar.signals[:some_signal]`.
```ruby
1# Setup with request
2datastar = Datastar.new(request:, response:)
3
4# Read signals
5some_signal = datastar.signals[:some_signal]
```
--------------------------------
### Ruby SDK for SSE Patch Signals
Source: https://data-star.dev/docs
Example using the Datastar Ruby SDK to create a streaming response and patch signals. It demonstrates how to instantiate a Datastar::Dispatcher and send patch signals with a delay.
```ruby
1require 'datastar'
2
3# Create a Datastar::Dispatcher instance
4
5datastar = Datastar.new(request:, response:)
6
7# In a Rack handler, you can instantiate from the Rack env
8# datastar = Datastar.from_rack_env(env)
9
10# Start a streaming response
11datastar.stream do |sse|
12 # Patches signals
13 sse.patch_signals(hal: 'Affirmative, Dave. I read you.')
14
15 sleep 1
16
17 sse.patch_signals(hal: '...')
18end
```
--------------------------------
### Go SDK for SSE Patch Signals
Source: https://data-star.dev/docs
Example using the Datastar Go SDK to create an SSE generator and patch signals. It shows how to send patch signal data and include a delay.
```go
1import (
2 "github.com/starfederation/datastar-go/datastar"
3)
4
5// Creates a new `ServerSentEventGenerator` instance.
6sse := datastar.NewSSE(w, r)
7
8// Patches signals
9sse.PatchSignals([]byte(`{hal: 'Affirmative, Dave. I read you.'}`))
10
11time.Sleep(1 * time.Second)
12
13sse.PatchSignals([]byte(`{hal: '...'}`))
```
--------------------------------
### Datastar Runtime Error Example
Source: https://data-star.dev/docs
Presents an example of a Datastar runtime error due to an invalid attribute key (`data-text-foo`), showing the console output with error details and a link to more information.
```log
Uncaught datastar runtime error: textKeyNotAllowed
More info: https://data-star.dev/errors/key_not_allowed?metadata=%7B%22plugin%22%3A%7B%22name%22%3A%22text%22%2C%22type%22%3A%22attribute%22%7D%2C%22element%22%3A%7B%22id%22%3A%22%22%2C%22tag%22%3A%22DIV%22%7D%2C%22expression%22%3A%7B%22rawKey%22%3A%22textFoo%22%2C%22key%22%3A%22foo%22%2C%22value%22%3A%22%22%2C%22fnContent%22%3A%22%22%7D%7D
Context: {
"plugin": {
"name": "text",
"type": "attribute"
},
"element": {
"id": "",
"tag": "DIV"
},
"expression": {
"rawKey": "textFoo",
"key": "foo",
"value": "",
"fnContent": ""
}
}
```
--------------------------------
### Datastar Action Options
Source: https://data-star.dev/docs
Explains the available options for Datastar actions, which are passed as a second argument.
```APIDOC
## Datastar Action Options
All Datastar actions accept an `options` object as their second argument to customize behavior.
### Options Available:
- **`contentType`** (`string`): Specifies the content type for the request. Accepts `json` (default) or `form`. `form` content type triggers form validation and submission without sending signals.
- **`filterSignals`** (`object`): Filters signals based on inclusion and exclusion criteria.
- `include` (`RegExp`): Regular expression to match signal paths to include. Defaults to all signals (`/.*/`).
- `exclude` (`RegExp`): Regular expression to exclude specific signal paths. Defaults to signals without a `_` prefix (`/(^_|._).*/`).
- **`selector`** (`string` | `null`): Specifies a form element to use when `contentType` is `form`. If `null`, the closest form is used. Defaults to `null`.
- **`headers`** (`object`): An object containing custom headers to send with the request.
- **`openWhenHidden`** (`boolean`): Determines if the connection should remain open when the page is hidden. Defaults to `false`.
- **`retry`** (`string`): Configures retry behavior for requests. Options include `'auto'` (default), `'error'`, `'always'`, and `'never'`.
- **`retryInterval`** (`number`): The interval in milliseconds between retries. Defaults to `1000`.
- **`retryScaler`** (`number`): A multiplier for scaling retry wait times. Defaults to `2`.
- **`retryMaxWaitMs`** (`number`): The maximum wait time in milliseconds between retries. Defaults to `30000`.
- **`retryMaxCount`** (`number`): The maximum number of retry attempts. Defaults to `10`.
- **`requestCancellation`** (`string` | `AbortController`): Controls request cancellation behavior. Options include `'auto'` (default), `'disabled'`, or an `AbortController` instance.
```
--------------------------------
### Datastar Backend SDKs
Source: https://data-star.dev/docs
Overview of the available backend Software Development Kits (SDKs) for Datastar, simplifying the generation of SSE events.
```APIDOC
# SDKs
Datastar provides backend SDKs to simplify the process of generating SSE events. Below is a list of available SDKs by language:
- **Clojure**: SDK and helper libraries available.
- **C# (.NET)**: SDK for working with Datastar.
- **Go**: SDK available.
- **Java**: SDK and examples available.
- **Kotlin**: SDK available.
- **PHP**: SDK available.
- **Craft CMS**: Plugin for integrating Datastar with Craft CMS.
- **Laravel**: Package for integrating Datastar with Laravel.
- **Python**: SDK and PyPI package available.
- **Ruby**: SDK available.
- **Rust**: SDK available.
- **Rama**: Module for integrating Datastar with Rama (Rust-based HTTP proxy).
```
--------------------------------
### Java SDK for SSE Patch Signals
Source: https://data-star.dev/docs
Example using the Datastar Java SDK to send SSE patch signals. It demonstrates creating a `ServerSentEventGenerator` and sending patch signal data with a delay.
```java
1import starfederation.datastar.utils.ServerSentEventGenerator;
2
3// Creates a new `ServerSentEventGenerator` instance.
4AbstractResponseAdapter responseAdapter = new HttpServletResponseAdapter(response);
5ServerSentEventGenerator generator = new ServerSentEventGenerator(responseAdapter);
6
7// Patches signals.
8generator.send(PatchSignals.builder()
9 .data("{\"hal\": \"Affirmative, Dave. I read you.\"}")
10 .build()
11);
12
13Thread.sleep(1000);
14
15generator.send(PatchSignals.builder()
16 .data("{\"hal\": \"...\"}")
17 .build()
18);
```
--------------------------------
### Patch DOM Elements with Python datastar_py
Source: https://data-star.dev/guide/getting_started
Shows how to patch HTML elements using the Python datastar_py library. This asynchronous example yields SSE patch elements, waits for a second, and then yields another patch element to update the DOM.
```python
from datastar_py import ServerSentEventGenerator as SSE
from datastar_py.sanic import datastar_response
import asyncio
@app.get('/open-the-bay-doors')
@datastar_response
async def open_doors(request):
yield SSE.patch_elements('
')
```
--------------------------------
### PHP SDK for SSE Patch Signals
Source: https://data-star.dev/docs
Example using the Datastar PHP SDK to generate SSE patch signals. It demonstrates creating a `ServerSentEventGenerator` and sending patch signal data with a delay.
```php
1use starfederation\datastar\ServerSentEventGenerator;
2
3// Creates a new `ServerSentEventGenerator` instance.
4$sse = new ServerSentEventGenerator();
5
6// Patches signals.
7$sse->patchSignals(['hal' => 'Affirmative, Dave. I read you.']);
8
9sleep(1);
10
11$sse->patchSignals(['hal' => '...']);
```
--------------------------------
### Send GET Request with Datastar
Source: https://data-star.dev/guide/getting_started
This snippet demonstrates how to use the `@get()` action in Datastar to send a GET request to a specified URL. The response, if HTML, will be morphed into the DOM based on element IDs. This is useful for fetching data or triggering backend actions that update the UI.
```html
```
--------------------------------
### Datastar Attribute Order and Initialization
Source: https://data-star.dev/docs
Demonstrates the order of attribute processing in Datastar, specifically highlighting the importance of `data-indicator` preceding `data-init` for fetch requests.
```html
```
--------------------------------
### Datastar Attribute Casing Conventions
Source: https://data-star.dev/docs
Explains Datastar's handling of attribute casing, converting `data-*` attributes to `camelCase` for signals and `kebab-case` for other attributes by default. Includes examples of manual casing control using `__case` and object syntax.
```html
```
--------------------------------
### GET Request with @get()
Source: https://data-star.dev/docs
Sends a GET request to a specified URI using the Fetch API. The response must contain Datastar SSE events. Supports options for controlling request behavior, like `openWhenHidden` and `contentType`.
```html
```
--------------------------------
### Kotlin SDK for SSE Patch Signals
Source: https://data-star.dev/docs
Example using the Datastar Kotlin SDK to generate SSE patch signals. It shows how to create a `ServerSentEventGenerator` and send patch signal data with a delay.
```kotlin
1val generator = ServerSentEventGenerator(response)
2
3generator.patchSignals(
4 signals = """{"hal": "Affirmative, Dave. I read you."} """,
5)
6
7Thread.sleep(ONE_SECOND)
8
9generator.patchSignals(
10 signals = """{"hal": "..."} """,
11)
```
--------------------------------
### Customizing Datastar Request Cancellation
Source: https://data-star.dev/docs
Shows how to customize request cancellation behavior in Datastar. The first example disables automatic cancellation, allowing multiple concurrent requests. The second example demonstrates using a custom AbortController for fine-grained control over request cancellation.
```html
```
--------------------------------
### Response Handling
Source: https://data-star.dev/docs
Details how Datastar handles different response content types from the backend.
```APIDOC
## Response Handling
Datastar automatically handles various response content types:
- **`text/event-stream`**: Processes standard Server-Sent Events (SSE) with Datastar SSE events.
- **`text/html`**: Patches HTML elements into the DOM.
- **`application/json`**: Patches JSON encoded signals.
- **`text/javascript`**: Executes JavaScript code in the browser.
### `text/html` Response Headers:
When returning `text/html`, the server can optionally include the following headers to control patching behavior:
- **`datastar-selector`** (`string`): A CSS selector specifying the target elements for patching.
- **`datastar-mode`** (`string`): The patching mode. Options include `outer`, `inner`, `remove`, `replace`, `prepend`, `append`, `before`, `after`. Defaults to `outer`.
- **`datastar-use-view-transition`** (`boolean`): Enables the use of the View Transition API for patching. Defaults to `false`.
#### Example HTML Response Headers:
```javascript
response.headers.set('Content-Type', 'text/html');
response.headers.set('datastar-selector', '#my-element');
response.headers.set('datastar-mode', 'inner');
response.body = '
New content
';
```
```
--------------------------------
### Including Datastar Aliased Bundle
Source: https://data-star.dev/docs
Shows how to include the Datastar framework with aliased attributes using a script tag pointing to a CDN.
```html
```
--------------------------------
### Python SDK for SSE Patch Signals
Source: https://data-star.dev/docs
Example using the Datastar Python SDK with a Sanic web framework integration to send SSE patch signals. It shows how to yield SSE events and include asynchronous delays.
```python
1from datastar_py import ServerSentEventGenerator as SSE
2from datastar_py.sanic import datastar_response
3
4@app.get('/do-you-read-me')
5@datastar_response
6async def open_doors(request):
7 yield SSE.patch_signals({"hal": "Affirmative, Dave. I read you."})
8 await asyncio.sleep(1)
9 yield SSE.patch_signals({"hal": "..."})
```
--------------------------------
### Patch Elements using SSE (C#)
Source: https://data-star.dev/guide/getting_started
This C# code demonstrates how to use Datastar's SDK to patch elements into the DOM via Server-Sent Events (SSE). It sets up Datastar as a service and then, within an HTTP GET handler, sends an initial message and updates it after a delay. This allows for dynamic UI updates in response to backend events.
```csharp
using StarFederation.Datastar.DependencyInjection;
// Adds Datastar as a service
builder.Services.AddDatastar();
app.MapGet("/", async (IDatastarService datastarService) =>
{
// Patches elements into the DOM.
await datastarService.PatchElementsAsync(@"
");
});
```
--------------------------------
### Content Security Policy Configuration
Source: https://data-star.dev/docs
This example demonstrates how to configure a Content Security Policy (CSP) to allow DataStar to evaluate expressions using the `Function()` constructor. The `unsafe-eval` directive must be included in the `script-src` directive.
```html
```
--------------------------------
### Python SSE Event Handling with Datastar
Source: https://data-star.dev/docs
This Python example shows how to use Datastar's `ServerSentEventGenerator` within a Litestar endpoint to return SSE events. It demonstrates returning a `DatastarResponse` containing both patched elements and signals.
```python
1from datastar_py import ServerSentEventGenerator as SSE
2from datastar_py.litestar import DatastarResponse
3
4async def endpoint():
5 return DatastarResponse([
6 SSE.patch_elements('
What do you put in a toaster?
'),
7 SSE.patch_signals({"response": "", "answer": "bread"})
8 ])
```
--------------------------------
### Datastar Expressions with Signals and Element Access
Source: https://data-star.dev/docs
Illustrates the use of Datastar expressions within `data-*` attributes, demonstrating how to access signals (prefixed with `$`) and the element context (`el`).
```html
```
--------------------------------
### Datastar Expression: Multiple Statements
Source: https://data-star.dev/docs
This HTML example shows how to execute multiple statements within a single Datastar expression by separating them with a semicolon, useful for updating signals and triggering actions.
```html
```
--------------------------------
### Clojure SDK for SSE Patch Signals
Source: https://data-star.dev/docs
Example using the Datastar Clojure SDK to generate SSE events for patching signals. It shows how to create an SSE response and send patch signals with a delay.
```clojure
1;; Import the SDK's api and your adapter
2(require
3 '[starfederation.datastar.clojure.api :as d*]
4 '[starfederation.datastar.clojure.adapter.http-kit :refer [->sse-response on-open]])
5
6;; in a ring handler
7(defn handler [request]
8 ;; Create an SSE response
9 (->sse-response request
10 {on-open
11 (fn [sse]
12 ;; Patches signal.
13 (d*/patch-signals! sse "{hal: 'Affirmative, Dave. I read you.'}")
14 (Thread/sleep 1000)
15 (d*/patch-signals! sse "{hal: '...'}"))}))
```
--------------------------------
### HTML for Nesting Signals in Datastar
Source: https://data-star.dev/docs
Demonstrates how to use HTML attributes to define nested signals in Datastar. It shows examples using dot-notation, object syntax, and two-way binding for attributes like `data-signals` and `data-bind`.
```html
1
```
```html
1
```
```html
1
```
```html
1
2
5
```
--------------------------------
### Show Loading Indicator During Request with Data-Star
Source: https://data-star.dev/docs
This example uses the `data-indicator` attribute to manage a loading state. The `data-indicator:fetching` attribute sets a signal to true while a request is in flight and false otherwise. This signal can then be used with `data-show` or `data-class` to display loading indicators. It requires an element with `id='question'` and a button to trigger the request.
```html
```
--------------------------------
### Reading Nested Signals in Kotlin (Ktor)
Source: https://data-star.dev/docs
Provides an example of reading signals in Kotlin using the Ktor framework. It defines a `Signals` data class and uses `Json.decodeFromString` with a `jsonUnmarshaller` to parse the request body.
```kotlin
1@Serializable
2data class Signals(
3 val foo: String,
4)
5
6val jsonUnmarshaller: JsonUnmarshaller = { json -> Json.decodeFromString(json) }
7
8val request: Request =
9 postRequest(
10 body =
11 """
12 {
13 "foo": "bar"
14 }
15 """.trimIndent()
16)
17
18val signals = readSignals(request, jsonUnmarshaller)
```
--------------------------------
### Install Datastar from local file
Source: https://data-star.dev/guide
If you prefer to host Datastar yourself, include the script from its local path after downloading or bundling it.
```html
```
--------------------------------
### Send Multiple SSE Events (Patch Elements and Signals)
Source: https://data-star.dev/docs
This showcases sending multiple Server-Sent Events (SSE) in a single response. It includes examples for patching HTML elements and sending patch signals, demonstrating the flexibility of SSE for real-time updates.
```datastar
(d*/patch-elements! sse "
');
stream.patchSignals({'answer': '...', 'prize': '...'});
```
--------------------------------
### data-init with Delay Modifier
Source: https://data-star.dev/docs
Demonstrates using the `__delay` modifier with `data-init` to introduce a delay before executing the initialization expression. This allows for controlled timing of initial actions.
```html
```
--------------------------------
### Kotlin SDK Example
Source: https://data-star.dev/how_tos/load_more_list_items
Example implementation in Kotlin demonstrating how to read signals and generate Server-Sent Events for updating the UI.
```APIDOC
## Kotlin SDK Example
### Description
This Kotlin code snippet shows how to read signals from a request and use `ServerSentEventGenerator` to send patch events for elements and signals, or to remove elements.
### Method
N/A (Server-side logic)
### Endpoint
N/A (Server-side logic)
### Parameters
#### Query Parameters
N/A
#### Request Body
N/A (Signals are read from request context)
### Request Example
```kotlin
@Serializable
data class OffsetSignals(
val offset: Int,
)
val signals =
readSignals(
request,
{ json: String -> Json.decodeFromString(json) },
)
val max = 5
val limit = 1
val offset = signals.offset
val generator = ServerSentEventGenerator(response)
// Logic to patch elements, signals, or remove elements based on offset
// (Illustrative, actual implementation details may vary)
if (offset < max) {
// Example: Patching new item
// generator.patchElements(htmlElement, PatchMode.Append, "#list")
// Example: Patching signals
// generator.patchSignals(OffsetSignals(offset + limit))
} else {
// Example: Removing button
// generator.removeElement("#load-more")
}
```
### Response
#### Success Response (200)
Server-Sent Events (SSE) containing `datastar-patch-elements` and `datastar-patch-signals` events.
#### Response Example
```
# See Backend Response section for SSE examples
```
```
--------------------------------
### Trigger GET Request on Click with Data-Star
Source: https://data-star.dev/docs
This code illustrates how to use the `data-on:click` attribute to trigger a `GET` request to a specified endpoint when an element is clicked. It also shows how to bind signals and computed properties for dynamic UI updates. The server response can modify DOM elements and signals.
```html
You answered “”.
That is correct ✅
The correct answer is “” 🤷
```
--------------------------------
### Go SDK Example
Source: https://data-star.dev/how_tos/load_more_list_items
Example implementation in Go using the Datastar SDK for handling HTTP requests and sending Server-Sent Events.
```APIDOC
## Go SDK Example
### Description
This Go code demonstrates how to use the Datastar SDK to handle incoming requests, read signals, and send SSE events to patch elements, append content, and update signals or remove elements.
### Method
GET
### Endpoint
`/how_tos/load_more/data` (or similar, triggered by client)
### Parameters
#### Query Parameters
N/A
#### Request Body
N/A (Signals are read from request context)
### Request Example
```go
import (
"fmt"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/starfederation/datastar-go/datastar"
)
type OffsetSignals struct {
Offset int `json:"offset"`
}
signals := &OffsetSignals{}
if err := datastar.ReadSignals(r, signals); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
max := 5
limit := 1
offset := signals.Offset
sse := datastar.NewSSE(w, r)
if offset < max {
newOffset := offset + limit
sse.PatchElements(fmt.Sprintf(`
Item %d
`, newOffset),
datastar.WithSelectorID("list"),
datastar.WithModeAppend(),
)
if newOffset < max {
sse.PatchSignals([]byte(fmt.Sprintf(`{offset: %d}`, newOffset)))
} else {
sse.RemoveElements(`#load-more`)
}
}
```
### Response
#### Success Response (200)
Server-Sent Events (SSE) containing `datastar-patch-elements` and `datastar-patch-signals` events.
#### Response Example
```
# See Backend Response section for SSE examples
```
```
--------------------------------
### C#: Registering and Using Datastar Service for DOM Patching
Source: https://data-star.dev/docs
This C# code demonstrates how to register Datastar as a service and then use its `PatchElementsAsync` method to update the DOM. It simulates sending an initial message and then updating it after a delay.
```csharp
1using StarFederation.Datastar.DependencyInjection;
2
3// Adds Datastar as a service
4builder.Services.AddDatastar();
5
6app.MapGet("/", async (IDatastarService datastarService) =>
7{
8 // Patches elements into the DOM.
9 await datastarService.PatchElementsAsync(@"
");
14});
```
--------------------------------
### Reading Signals in Python (FastAPI)
Source: https://data-star.dev/docs
Shows how to read signals in Python using FastAPI and the Datastar library. It utilizes the `@datastar_response` decorator and the `read_signals` utility function to get signal data from the request.
```python
1from datastar_py.fastapi import datastar_response, read_signals
2
3@app.get("/updates")
4@datastar_response
5async def updates(request: Request):
6 # Retrieve a dictionary with the current state of the signals from the frontend
7 signals = await read_signals(request)
```
--------------------------------
### data-init for Initialization Expressions
Source: https://data-star.dev/docs
Explains the `data-init` attribute, which executes an expression upon initialization. This can occur during page load, DOM patching, or attribute modification, useful for setting initial states.
```html
```
--------------------------------
### Server-Sent Events (SSE) for Datastar Patch Elements with Script
Source: https://data-star.dev/docs
An example of Server-Sent Events (SSE) formatted for Datastar. This specifically shows how to send a 'datastar-patch-elements' event containing HTML, including a script tag, to be rendered and executed on the client.
```text
event: datastar-patch-elements
data: elements
data:
data:
```
--------------------------------
### Patch DOM Elements with PHP ServerSentEventGenerator
Source: https://data-star.dev/guide/getting_started
Demonstrates patching HTML elements into the DOM using the PHP ServerSentEventGenerator class. It sends an initial message, waits for 1 second, and then sends a subsequent message to update the same element.
```php
use starfederation\datastar\ServerSentEventGenerator;
// Creates a new `ServerSentEventGenerator` instance.
$sse = new ServerSentEventGenerator();
// Patches elements into the DOM.
$sse->patchElements(
'
I’m sorry, Dave. I’m afraid I can’t do that.
'
);
sleep(1);
$sse->patchElements(
'
Waiting for an order...
'
);
```
--------------------------------
### Patching Elements and Signals
Source: https://data-star.dev/docs
Demonstrates how to patch HTML elements into the DOM and update frontend signals using the `stream.patchElements()` and `stream.patchSignals()` functions.
```APIDOC
## PATCH /actions/quiz (Simulated)
### Description
This endpoint is simulated via frontend actions. It's triggered by a user click and demonstrates patching HTML elements into the DOM and updating frontend signals. The `stream.patchElements()` function updates a specific DOM element, and `stream.patchSignals()` updates signal values.
### Method
GET (Triggered by frontend action)
### Endpoint
/actions/quiz
### Parameters
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
// Frontend JavaScript triggering the action
stream.patchElements(`
What do you put in a toaster?
`);
stream.patchSignals({'response': '', 'answer': 'bread'});
```
### Response
#### Success Response (200)
Signals and DOM elements are updated directly by the frontend functions. The server's response is interpreted as events to modify the DOM and signals.
#### Response Example
```json
// Example of server-sent events that would trigger frontend updates
// These are not direct JSON responses but instructions for the frontend.
{
"type": "patch_elements",
"payload": {
"html": "
What do you put in a toaster?
"
}
}
{
"type": "patch_signals",
"payload": {
"signals": {
"response": "",
"answer": "bread"
}
}
}
```
```
--------------------------------
### Clojure SDK Example
Source: https://data-star.dev/how_tos/load_more_list_items
Example implementation in Clojure using the Datastar SDK to handle the 'load more' logic, including patching elements and signals.
```APIDOC
## Clojure SDK Example
### Description
This Clojure code demonstrates how to handle the `load_more` request. It reads the current offset, patches the new item into the `#list` container using append mode, and either patches the updated offset signal or removes the load more button if the maximum offset is reached.
### Method
POST
### Endpoint
`/how_tos/load_more/data` (or similar, triggered by client)
### Parameters
#### Query Parameters
N/A
#### Request Body
N/A (Signals are read from request headers/context)
### Request Example
```clojure
(require
'[starfederation.datastar.clojure.api :as d*]
'[starfederation.datastar.clojure.adapter.http-kit :refer [->sse-response on-open]]
'[some.hiccup.library :refer [html]]
'[some.json.library :refer [read-json-str write-json-str]]))
(def max-offset 5)
(defn handler [ring-request]
(->sse-response ring-request
{on-open
(fn [sse]
(let [d*-signals (-> ring-request d*/get-signals read-json-str)
offset (get d*-signals "offset")
limit 1
new-offset (+ offset limit)]
(d*/patch-elements! sse
(html [:div "Item " new-offset])
{d*/selector "#list"
d*/merge-mode d*/mm-append})
(if (< new-offset max-offset)
(d*/patch-signals! sse (write-json-str {"offset" new-offset}))
(d*/remove-fragment! sse "#load-more")
(d*/close-sse! sse)))}
))
```
### Response
#### Success Response (200)
Server-Sent Events (SSE) containing `datastar-patch-elements` and `datastar-patch-signals` events.
#### Response Example
```
# See Backend Response section for SSE examples
```
```
--------------------------------
### Generate SSE for Patching Elements (Kotlin)
Source: https://data-star.dev/guide/getting_started
This Kotlin code shows how to use Datastar's `ServerSentEventGenerator` to patch elements into the DOM via SSE. It sends an initial HTML element and then updates it after a delay, illustrating real-time DOM manipulation. This approach is effective for dynamic user interfaces.
```kotlin
val generator = ServerSentEventGenerator(response)
generator.patchElements(
elements = """
I’m sorry, Dave. I’m afraid I can’t do that.
""",
)
Thread.sleep(ONE_SECOND)
```
--------------------------------
### Data Indicator for Loading States
Source: https://data-star.dev/docs
Shows how to use the `data-indicator` attribute to manage loading states. The `data-indicator` attribute sets a signal to `true` while a request is in flight, allowing for visual loading indicators.
```APIDOC
## GET /actions/quiz (with Loading Indicator)
### Description
This endpoint demonstrates using the `data-indicator` attribute to visually indicate when a request is in progress. The `data-indicator:` attribute on an element will set the specified signal to `true` during the request and `false` afterwards. This signal can then be used to conditionally display loading indicators.
### Method
GET
### Endpoint
/actions/quiz
### Parameters
#### Query Parameters
None
#### Request Body
None
### Request Example
```html
```
### Response
#### Success Response (200)
Upon successful completion, the `fetching` signal will be set to `false`, and any element bound to this signal (e.g., via `data-class:loading`) will update accordingly.
#### Response Example
```json
// Server response for a successful request (content depends on the action)
{
"message": "Question fetched successfully"
}
```
```
--------------------------------
### Configure Datastar GET Request with Options
Source: https://data-star.dev/reference/actions
This example demonstrates how to configure a Datastar GET request using various options. It includes signal filtering, custom headers, enabling open-when-hidden, and disabling request cancellation. This is useful for fine-tuning network requests and their behavior.
```html
```
--------------------------------
### SSE Event: datastar-patch-signals
Source: https://data-star.dev/docs
Handles patching of signals into the existing signals on the page. Allows for conditional updates and setting signal values.
```APIDOC
## SSE Event: datastar-patch-signals
### Description
Patches signals into the existing signals on the page. The `onlyIfMissing` directive controls whether to update signals only if they do not already exist. The `signals` directive expects a valid `data-signals` attribute value.
### Event Type
`datastar-patch-signals`
### Data Directives
- **`onlyIfMissing `**: If true, updates signals only if a signal with that name does not yet exist. Defaults to `false`.
- **`signals `**: A JSON object representing the signals to patch, where keys are signal names and values are their new values. Setting a value to `null` removes the signal.
### Request Example (Patching Signals)
```
event: datastar-patch-signals
data: signals {foo: 1, bar: 2}
```
### Request Example (Removing Signals)
```
event: datastar-patch-signals
data: signals {foo: null, bar: null}
```
### Request Example (Conditional Patching)
```
event: datastar-patch-signals
data: onlyIfMissing true
data: signals {foo: 1, bar: 2}
```
### Response
N/A (This is a client-side event triggered by the server).
```
--------------------------------
### Set Multiple HTML Attributes using data-attr
Source: https://data-star.dev/docs
This example shows how to use the `data-attr` attribute to set multiple HTML attributes on an element simultaneously. It accepts a key-value pair object where keys are attribute names and values are Datastar expressions.
```html
```
--------------------------------
### Request Cancellation Behavior
Source: https://data-star.dev/docs
Explains the default request cancellation behavior and how to control it.
```APIDOC
## Request Cancellation
By default, Datastar automatically cancels any ongoing request on the same element when a new request is initiated. This prevents conflicts from rapid user interactions.
### Default Behavior Example:
```html
```
This cancellation is element-specific; requests on different elements can run concurrently.
### Controlling Request Cancellation:
You can modify this behavior using the `requestCancellation` option:
- **Allow Concurrent Requests:**
```html
```
- **Custom Abort Controller:**
```html
```
```
--------------------------------
### C# SDK Example
Source: https://data-star.dev/how_tos/load_more_list_items
Example implementation in C# using the Datastar SDK for ASP.NET Core to manage the 'load more' functionality.
```APIDOC
## C# SDK Example
### Description
This C# code demonstrates a minimal ASP.NET Core application using Datastar. The `/more` endpoint reads signals, patches new elements with append mode, and updates signals or removes the button based on the offset.
### Method
GET
### Endpoint
`/more`
### Parameters
#### Query Parameters
N/A
#### Request Body
N/A (Signals are read from request context)
### Request Example
```csharp
using System.Text.Json;
using StarFederation.Datastar;
using StarFederation.Datastar.DependencyInjection;
public class Program
{
public record OffsetSignals(int offset);
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDatastar();
var app = builder.Build();
app.MapGet("/more", async (IDatastarService datastarService) =>
{
var max = 5;
var limit = 1;
var signals = await datastarService.ReadSignalsAsync();
var offset = signals.offset;
if (offset < max)
{
var newOffset = offset + limit;
await datastarService.PatchElementsAsync($"
Item {newOffset}
", new()
{
Selector = "#list",
PatchMode = PatchElementsMode.Append,
});
if (newOffset < max)
await datastarService.PatchSignalsAsync(new OffsetSignals(newOffset));
else
await datastarService.RemoveElementAsync("#load-more");
}
});
app.Run();
}
}
```
### Response
#### Success Response (200)
HTTP 200 OK with response body handled by Datastar client-side logic based on signals and patched elements.
#### Response Example
N/A (Response is typically SSE or handled via Datastar's client-side state management)
```
--------------------------------
### Reading Signals in PHP
Source: https://data-star.dev/docs
Demonstrates how to read all signals from an incoming request in PHP using the `ServerSentEventGenerator::readSignals()` helper function provided by Datastar.
```php
1use starfederation\datastar\ServerSentEventGenerator;
2
3// Reads all signals from the request.
4$signals = ServerSentEventGenerator::readSignals();
```
--------------------------------
### Generate SSE for Patching Elements (Java)
Source: https://data-star.dev/guide/getting_started
This Java snippet demonstrates generating Server-Sent Events (SSE) to patch elements into the DOM using Datastar's Java library. It initializes an SSE generator and then sends an initial patch, followed by an update after a one-second delay, facilitating dynamic content updates.
```java
import starfederation.datastar.utils.ServerSentEventGenerator;
// Creates a new `ServerSentEventGenerator` instance.
AbstractResponseAdapter responseAdapter = new HttpServletResponseAdapter(response);
ServerSentEventGenerator generator = new ServerSentEventGenerator(responseAdapter);
// Patches elements into the DOM.
generator.send(PatchElements.builder()
.data("