Can't access websocket from within callbacks
notpeelz opened this issue · comments
I'm trying to use the use_websocket_with_options
hook to send a message immediately upon connecting to the server.
#[function_component(App)]
pub fn app() -> Html {
let ws = yew_hooks::use_websocket_with_options(
"ws://mywebsocket".into(),
yew_hooks::UseWebSocketOptions {
onopen: Some(Box::new(|_| {
// This doesn't compile
ws.send("test".into());
})),
..Default::default()
},
);
html! {
<main>
</main>
}
}
How can I access ws
from inside of this closure? UseWebSocketHandle
doesn't have a way to change the websocket callbacks after initialization.
Update:
I managed to work around it using use_effect_with_deps
:
let addr = "ws://mywebsocket";
let ws = use_websocket(addr.into());
{
let ws = ws.clone();
let ready_state = ws.ready_state.clone();
use_effect_with_deps(
move |ready_state| {
if **ready_state == UseWebSocketReadyState::Open {
info!("Open");
ws.send("a".into());
}
},
ready_state,
);
}