Function use_websocket_with_options

Source
pub fn use_websocket_with_options<'hook>(
    url: String,
    options: UseWebSocketOptions,
) -> impl 'hook + Hook<Output = UseWebSocketHandle>
Expand description

This hook communicates with WebSocket with options.

§Example

use yew_hooks::prelude::*;

#[function_component(UseWebSocket)]
fn web_socket() -> Html {
    let history = use_list(vec![]);

    let ws = {
        let history = history.clone();
        use_websocket_with_options(
            "wss://echo.websocket.events/".to_string(),
            UseWebSocketOptions {
                // Receive message by callback `onmessage`.
                onmessage: Some(Box::new(move |message| {
                    history.push(format!("[recv]: {}", message));
                })),
                manual: Some(true),
                ..Default::default()
            },
        )
    };
    let onclick = {
        let ws = ws.clone();
        let history = history.clone();
        Callback::from(move |_| {
            let message = "Hello, world!".to_string();
            ws.send(message.clone());
            history.push(format!("[send]: {}", message));
        })
    };
    let onopen = {
        let ws = ws.clone();
        Callback::from(move |_| {
            ws.open();
        })
    };

    html! {
        <>
            <p>
                <button onclick={onopen} disabled={*ws.ready_state != UseWebSocketReadyState::Closed}>{ "Connect" }</button>
                <button {onclick} disabled={*ws.ready_state != UseWebSocketReadyState::Open}>{ "Send with options" }</button>
            </p>
            <p>
                <b>{ "Message history: " }</b>
            </p>
            {
                for history.current().iter().map(|message| {
                    html! {
                        <p>{ message }</p>
                    }
                })
            }
        </>
    }
}

§Note

When used in function components and hooks, this hook is equivalent to:

pub fn use_websocket_with_options(
    url: String,
    options: UseWebSocketOptions,
) -> UseWebSocketHandle {
    /* implementation omitted */
}