Skip to content

Can't access websocket from within callbacks #27

Description

@notpeelz

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,
  );
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions