Function use_websocket

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

This hook communicates with WebSocket.

§Example

use yew_hooks::prelude::*;

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

    let ws = use_websocket("wss://echo.websocket.events/".to_string());
    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 history = history.clone();
        let ws = ws.clone();
        // Receive message by depending on `ws.message`.
        use_effect_with(
            ws.message,
            move |message| {
                if let Some(message) = &**message {
                    history.push(format!("[recv]: {}", message.clone()));
                }
                || ()
            },
        );
    }

    html! {
        <>
            <p>
                <button {onclick} disabled={*ws.ready_state != UseWebSocketReadyState::Open}>{ "Send" }</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(url: String) -> UseWebSocketHandle {
    /* implementation omitted */
}