Leptos-Use Guide

use_event_source

Reactive EventSource

An EventSource or Server-Sent-Events instance opens a persistent connection to an HTTP server, which sends events in text/event-stream format.

Usage

Values are decoded via the given Codec.

To use the JsonCodec, you will need to add the "serde" feature to your project's Cargo.toml. To use ProstCodec, add the feature "prost".

use leptos::*;
use leptos_use::{use_event_source, UseEventSourceReturn, utils::JsonCodec};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, PartialEq)]
pub struct EventSourceData {
    pub message: String,
    pub priority: u8,
}

#[component]
fn Demo() -> impl IntoView {
let UseEventSourceReturn {
    ready_state, data, error, close, ..
} = use_event_source::<EventSourceData, JsonCodec>("https://event-source-url");

view! { }
}

Create Your Own Custom Codec

All you need to do is to implement the StringCodec trait together with Default and Clone.

Named Events

You can define named events when using use_event_source_with_options.

use leptos::*;
use leptos_use::{use_event_source_with_options, UseEventSourceReturn, UseEventSourceOptions, utils::FromToStringCodec};

#[component]
fn Demo() -> impl IntoView {
let UseEventSourceReturn {
    ready_state, data, error, close, ..
} = use_event_source_with_options::<String, FromToStringCodec>(
    "https://event-source-url",
    UseEventSourceOptions::default()
        .named_events(["notice".to_string(), "update".to_string()])
);

view! { }
}

Immediate

Auto-connect (enabled by default).

This will call open() automatically for you, and you don't need to call it by yourself.

Auto-Reconnection

Reconnect on errors automatically (enabled by default).

You can control the number of reconnection attempts by setting reconnect_limit and the interval between them by setting reconnect_interval.

use leptos::*;
use leptos_use::{use_event_source_with_options, UseEventSourceReturn, UseEventSourceOptions, utils::FromToStringCodec};

#[component]
fn Demo() -> impl IntoView {
let UseEventSourceReturn {
    ready_state, data, error, close, ..
} = use_event_source_with_options::<bool, FromToStringCodec>(
    "https://event-source-url",
    UseEventSourceOptions::default()
        .reconnect_limit(5)         // at most 5 attempts
        .reconnect_interval(2000)   // wait for 2 seconds between attempts
);

view! { }
}

To disable auto-reconnection, set reconnect_limit to 0.

Server-Side Rendering

On the server-side, use_event_source will always return ready_state as ConnectionReadyState::Closed, data, event and error will always be None, and open and close will do nothing.

Types

Source

SourceDocs