fix(fullstack): prevent AlreadyBorrowed panic in WebSocket recv() (#5300)
This commit is contained in:
1 parent
d75d9642ef
commit
64cc42e16e
4 files changed
+80
-51
No files matched your search
@@ -24,21 +24,25 @@ fn main() {
|
||||
}
|
||||
|
||||
fn app() -> Element {
|
||||
// Track the messages we've received from the server.
|
||||
let mut messages = use_signal(std::vec::Vec::new);
|
||||
|
||||
// The `use_websocket` wraps the `WebSocket` connection and provides a reactive handle to easily
|
||||
// send and receive messages and track the connection state.
|
||||
//
|
||||
// We can customize the websocket connection with the `WebSocketOptions` struct, allowing us to
|
||||
// set things like custom headers, protocols, reconnection strategies, etc.
|
||||
let mut socket = use_websocket(|| uppercase_ws("John Doe".into(), 30, WebSocketOptions::new()));
|
||||
// This signal is read inside the use_websocket closure, making it a reactive dependency.
|
||||
// Whenever it changes, the websocket will automatically re-connect.
|
||||
let mut name = use_signal(|| "John Doe".to_string());
|
||||
|
||||
let mut socket =
|
||||
use_websocket(move || uppercase_ws(name.cloned(), 30, WebSocketOptions::new()));
|
||||
|
||||
// Calling `.recv()` automatically waits for the connection to be established and deserializes
|
||||
// messages as they arrive.
|
||||
use_future(move || async move {
|
||||
while let Ok(msg) = socket.recv().await {
|
||||
messages.push(msg);
|
||||
loop {
|
||||
// Wait for the socket to connect
|
||||
_ = socket.connect().await;
|
||||
|
||||
// Loop poll with recv. Throws an error when the connection closes, making it possible
|
||||
// to run code before the socket re-connects when the name input changes
|
||||
while let Ok(msg) = socket.recv().await {
|
||||
messages.push(msg);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -46,6 +50,12 @@ fn app() -> Element {
|
||||
h1 { "WebSocket Example" }
|
||||
p { "Type a message and see it echoed back in uppercase!" }
|
||||
p { "Connection status: {socket.status():?}" }
|
||||
p { "Change your name to trigger a websocket re-connect" }
|
||||
input {
|
||||
placeholder: "Your name",
|
||||
value: "{name}",
|
||||
oninput: move |e| name.set(e.value()),
|
||||
}
|
||||
input {
|
||||
placeholder: "Type a message",
|
||||
oninput: move |e| async move { _ = socket.send(ClientEvent::TextInput(e.value())).await; },
|
||||
|
||||
Reference in new issue
Block a user