add agent but not working(yet)
This commit is contained in:
@ -1,16 +1,48 @@
|
||||
use yew::{function_component, html, use_state_eq, Callback, Html};
|
||||
use std::rc::Rc;
|
||||
|
||||
use yew::{function_component, html, use_context, use_state_eq, Callback, Html};
|
||||
use yew_agent::{prelude::{use_reactor_bridge, use_reactor_subscription}, reactor::{ReactorEvent, ReactorProvider}};
|
||||
|
||||
#[function_component]
|
||||
pub fn Counter() -> Html {
|
||||
let count_value = use_state_eq(||None);
|
||||
let counter = use_reactor_subscription::<crate::frontend::worker::Counter>();
|
||||
let callback = {
|
||||
let counter_handle = counter.clone();
|
||||
let count_value = count_value.clone();
|
||||
|
||||
Callback::from(move |_: yew::MouseEvent| {
|
||||
counter_handle.send(());
|
||||
|
||||
let count_default = Rc::new(0);
|
||||
let count_result = **(counter.iter().next().unwrap_or(&count_default));
|
||||
count_value.set(Some(count_result));
|
||||
})
|
||||
};
|
||||
|
||||
let counter_widget = if let Some(value) = *count_value {
|
||||
html! {
|
||||
<h1 class="mx-auto my-auto" onclick={callback}>{format!("{}", value)}</h1>
|
||||
}
|
||||
} else {
|
||||
html! {
|
||||
<h1 class="mx-auto my-auto" onclick={callback}>{"not yet"}</h1>
|
||||
}
|
||||
} ;
|
||||
|
||||
html! {
|
||||
<div class="w-full h-full flex">{"Counter: "}
|
||||
{counter_widget}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
#[function_component]
|
||||
pub fn CounterPage() -> Html {
|
||||
let counter = use_state_eq(|| 1);
|
||||
let counter_handle = counter.clone();
|
||||
let callback = Callback::from(move |_: yew::MouseEvent| {
|
||||
counter_handle.set(*counter_handle + 1);
|
||||
});
|
||||
|
||||
html! {
|
||||
<div class="w-full h-full flex">{"Counter: "}
|
||||
<h1 class="mx-auto my-auto" onclick={callback}>{format!("{}",*counter)}</h1>
|
||||
</div>
|
||||
<ReactorProvider<crate::frontend::worker::Counter> path="/worker.js">
|
||||
<Counter />
|
||||
</ReactorProvider<crate::frontend::worker::Counter>>
|
||||
}
|
||||
}
|
19
src/frontend/worker.rs
Normal file
19
src/frontend/worker.rs
Normal file
@ -0,0 +1,19 @@
|
||||
use yew_agent::prelude::*;
|
||||
use futures::sink::SinkExt;
|
||||
use futures::stream::StreamExt;
|
||||
|
||||
#[reactor(Counter)]
|
||||
pub async fn counter(mut scope: ReactorScope<(), u64>) {
|
||||
let mut count = 0;
|
||||
while let Some(input) = scope.next().await {
|
||||
count += 1;
|
||||
let _ = scope.send(count+1).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[reactor(Echo)]
|
||||
pub async fn echo(mut scope: ReactorScope<String, String>) {
|
||||
while let Some(input) = scope.next().await {
|
||||
let _ = scope.send(input).await;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user