Function leptos_use::use_broadcast_channel

source ·
pub fn use_broadcast_channel<T, C>(
    name: &str
) -> UseBroadcastChannelReturn<T, impl Fn(&T) + Clone, impl Fn() + Clone, C::Error>
where C: StringCodec<T> + Default + Clone,
Expand description

Reactive BroadcastChannel API.

Closes a broadcast channel automatically when the component is cleaned up.

§Demo

Link to Demo

§Usage

The BroadcastChannel interface represents a named channel that any browsing context of a given origin can subscribe to. It allows communication between different documents (in different windows, tabs, frames, or iframes) of the same origin.

Messages are broadcasted via a message event fired at all BroadcastChannel objects listening to the channel.

let UseBroadcastChannelReturn {
    is_supported,
    message,
    post,
    error,
    close,
    ..
} = use_broadcast_channel::<bool, FromToStringCodec>("some-channel-name");

post(&true);

close();

Just like with [use_storage] you can use different codecs for encoding and decoding.

// Data sent in JSON must implement Serialize, Deserialize:
#[derive(Serialize, Deserialize, Clone, PartialEq)]
pub struct MyState {
    pub playing_lego: bool,
    pub everything_is_awesome: String,
}

use_broadcast_channel::<MyState, JsonCodec>("everyting-is-awesome");

§Create Your Own Custom Codec

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