Function yew_hooks::use_web_socket_with_options
source · [−]pub fn use_web_socket_with_options(
url: String,
options: UseWebSocketOptions
) -> UseWebSocketHandleExpand description
This hook communicates with WebSocket with options.
Example
use yew_hooks::{
use_list, use_web_socket_with_options,
UseWebSocketOptions, UseWebSocketReadyState
};
#[function_component(UseWebSocket)]
fn web_socket() -> Html {
let history = use_list(vec![]);
let ws = {
let history = history.clone();
use_web_socket_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>
}
})
}
</>
}
}