Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't access websocket from within callbacks #27

Open
notpeelz opened this issue Feb 16, 2023 · 0 comments
Open

Can't access websocket from within callbacks #27

notpeelz opened this issue Feb 16, 2023 · 0 comments

Comments

@notpeelz
Copy link

notpeelz commented Feb 16, 2023

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,
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant