Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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 decoder. You can use any of the string codecs or a binary codec wrapped in Base64.

Please check the codec chapter to see what codecs are available and what feature flags they require.

use leptos::prelude::*;
use leptos_use_event_source::{use_event_source, UseEventSourceReturn};
use codee::string::JsonSerdeCodec;
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, message, error, close, ..
} = use_event_source::<EventSourceData, JsonSerdeCodec>("https://event-source-url");

view! { }
}

Named Events

You can define named events when using use_event_source_with_options.

use leptos::prelude::*;
use leptos_use_event_source::{use_event_source_with_options, UseEventSourceReturn, UseEventSourceOptions};
use codee::string::FromToStringCodec;

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

view! { }
}

Custom Event Handler

You can provide a custom on_event handler using use_event_source_with_options. on_event wil be run for every received event, including the built-in open, error, and message events, as well as any named events you have specified.

With the return value of on_event you can control, whether message and named events should be further processed by use_event_source (UseEventSourceOnEventReturn::ProcessMessage) or ignored (UseEventSourceOnEventReturn::IgnoreProcessingMessage).

By default, the handler returns UseEventSourceOnEventReturn::ProcessMessage.

use leptos::prelude::*;
use leptos_use_event_source::{use_event_source_with_options, UseEventSourceReturn, UseEventSourceOptions, UseEventSourceMessage, UseEventSourceOnEventReturn};
use codee::string::FromToStringCodec;

#[component]
fn Demo() -> impl IntoView {
// Custom example handler: log event name and check for named `custom_error` event
let custom_event_handler = |e: &web_sys::Event| {
    leptos::logging::log!("Received event: {}", e.type_());
    if e.type_() == "custom_error" {
        if let Ok(error_message) = UseEventSourceMessage::<String, FromToStringCodec>::try_from(e.clone()) {
            // Decoded successfully, log the error message
            leptos::logging::log!("Error message: {}", error_message.data);
            // skip processing this message event further
            return UseEventSourceOnEventReturn::IgnoreProcessingMessage;
        }
    }
    // Process other message events normally
    UseEventSourceOnEventReturn::ProcessMessage
};
let UseEventSourceReturn {
    ready_state, message, error, close, ..
} = use_event_source_with_options::<String, FromToStringCodec>(
    "https://event-source-url",
    UseEventSourceOptions::default()
        .named_events(["custom_error".to_string()])
        .on_event(custom_event_handler)
);

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::prelude::*;
use leptos_use_event_source::{use_event_source_with_options, UseEventSourceReturn, UseEventSourceOptions};
use leptos_use_core::ReconnectLimit;
use codee::string::FromToStringCodec;

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

view! { }
}

SendWrapped Return

The returned closures open and close are sendwrapped functions. They can only be called from the same thread that called use_event_source.

To disable auto-reconnection, set reconnect_limit to 0.

Server-Side Rendering

Make sure you follow the instructions in 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.

Installation

cargo add leptos-use-event-source

Options

UseEventSourceOptions

Options for use_event_source_with_options.

Every option is set with a builder method of the same name, e.g. UseEventSourceOptions::default().reconnect_limit(...). See also the API docs.

reconnect_limit

Type: ReconnectLimit

Retry times. Defaults to ReconnectLimit::Limited(3). Use ReconnectLimit::Infinite for infinite retries.

reconnect_interval

Type: u64

Retry interval in ms. Defaults to 3000.

on_failed

Type: Arc<dyn Fn() + Send + Sync>

On maximum retry times reached.

immediate

Type: bool

If true the EventSource connection will immediately be opened when calling this function. If false you have to manually call the open function. Defaults to true.

named_events

Type: Vec<String>

List of named events to listen for on the EventSource.

on_event

Type: Arc<dyn Fn(&web_sys::Event) -> UseEventSourceOnEventReturn + Send + Sync>

The on_event is called before processing any event inside of use_event_source. Return UseEventSourceOnEventReturn::Ignore to ignore further processing of the respective event in use_event_source, or UseEventSourceOnEventReturn::Use to process the event as usual.

Beware that ignoring processing the open and error events may yield unexpected results.

You may want to use UseEventSourceMessage::try_from() to access the event data.

Default handler returns UseEventSourceOnEventReturn::Use.

with_credentials

Type: bool

If CORS should be set to include credentials. Defaults to false.

_marker

Type: PhantomData<T>

Source

Source • Docs