8000 Can't access websocket from within callbacks · Issue #27 · jetli/yew-hooks · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Can't access websocket from within callbacks #27
Open
@notpeelz

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

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

      0