Hi, an friend of mine and me are trying to build an Dioxus app with an websocket.
The Websocket is inteded to be used to update some componenents.
But we couldn't find any examples how to send the received websocket data to the different components.
Is there any example we didn't find or can someone explain how this should/could be done?
#Using Websockets with Dioxus
1 messages · Page 1 of 1 (latest)
To make sure I understand the problem: Do you want to split the data you receive from the websocket based on the type of message and then forward those messages to child components?
I get an Json String form the Websocket which looks for example like this:
{
"type": "item",
"itemID": "",
"text": "",
"status": "",
"tableID": ""
}
i then want to send this data to an child componenet so it can update its contents and vice versa if i change something in an component via an textfield i want to send it to the Websocket
You can pass a futures mpsc channel to the child component for each type of message either through the props or context
Then in the child component you can use a use_future hook to read information from the websocket
You can write any changes back to the websocket in a use_resource which reruns when the signal changes
the futures mpsc channel you mentioned comes from the futures crate right?
Yes
Thank you very much. I will try to implment this. I have further questions i will be back
Hi, I am also working on the same project. I now have the following Implementation using the use_future
#[derive(Clone, Props)]
pub struct ComponentProps {
pub tx: Arc<mpsc::UnboundedSender<Value>>,
pub rx: Arc<mpsc::UnboundedReceiver<Value>>,
}
impl PartialEq for ComponentProps {
fn eq(&self, other: &Self) -> bool {
true
}
}
#[component]
pub fn Home(props: ComponentProps) -> Element {
let mut current_message = use_signal(|| json!(""));
let tx = Arc::clone(&props.tx);
let rx = Arc::clone(&props.rx);
use_future(move || async move {
let rx = Arc::clone(&rx);
async move {
let mut local_rx = rx.as_ref().to_owned();
while let Ok(Some(message)) = local_rx.try_next() {
current_message.set(message);
}
}
});
...
I am not quite sure if this is the correct way to use a use_future. I also have the problem, that I can't seem to resolve the rx (mpsc::UnboundedReciever) as the async move wants me to first copy the rx, which I am doing. Is there a better way of doing this?
We recently rolled our own custom hook/signal for subscribing to a websocket, might be a good reference
https://github.com/regolith-labs/ore-app/blob/master/src/hooks/resources/use_wss_sub.rs