State syncing
This commit is contained in:
+4
-29
@@ -13,6 +13,9 @@ fn app(cx: &Arc<Context>) -> View {
|
|||||||
let count = use_state(0);
|
let count = use_state(0);
|
||||||
let mount = use_mount_manual();
|
let mount = use_mount_manual();
|
||||||
|
|
||||||
|
// Sync state with children
|
||||||
|
use_sync_effect(cx, &count, |v| Count(v.clone()), &[&mount, &count]);
|
||||||
|
|
||||||
use_effect(
|
use_effect(
|
||||||
{
|
{
|
||||||
let count = count.clone();
|
let count = count.clone();
|
||||||
@@ -29,18 +32,6 @@ fn app(cx: &Arc<Context>) -> View {
|
|||||||
&[&mount],
|
&[&mount],
|
||||||
);
|
);
|
||||||
|
|
||||||
// Pass the count to the children
|
|
||||||
use_effect(
|
|
||||||
{
|
|
||||||
let count = count.clone();
|
|
||||||
let cx = cx.clone();
|
|
||||||
move || {
|
|
||||||
cx.emit_event(&Count(count.clone()));
|
|
||||||
}
|
|
||||||
},
|
|
||||||
&[&mount],
|
|
||||||
);
|
|
||||||
|
|
||||||
rsx! {
|
rsx! {
|
||||||
// Static scope
|
// Static scope
|
||||||
my_component (ctx, view) {
|
my_component (ctx, view) {
|
||||||
@@ -67,25 +58,9 @@ fn app(cx: &Arc<Context>) -> View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn my_component(cx: &Arc<Context>) -> View {
|
fn my_component(cx: &Arc<Context>) -> View {
|
||||||
let mount = use_mount();
|
// Sync state with parent
|
||||||
let count = use_sync_state(cx, 0, |Count(v)| v.get_dl());
|
let count = use_sync_state(cx, 0, |Count(v)| v.get_dl());
|
||||||
|
|
||||||
use_effect(
|
|
||||||
{
|
|
||||||
let count = count.clone();
|
|
||||||
move || loop {
|
|
||||||
std::thread::sleep(std::time::Duration::from_millis(500));
|
|
||||||
let mut count = count.get();
|
|
||||||
if *count > 5 {
|
|
||||||
*count = 0;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
*count += 1;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
&[&mount],
|
|
||||||
);
|
|
||||||
|
|
||||||
rsx! {
|
rsx! {
|
||||||
"Count: {count}"
|
"Count: {count}"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -189,3 +189,25 @@ pub fn use_sync_state<
|
|||||||
|
|
||||||
state
|
state
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn use_sync_effect<
|
||||||
|
T: Send + Sync + 'static,
|
||||||
|
Ev: 'static,
|
||||||
|
E: Fn(&State<T>) -> Ev + Send + Sync + 'static,
|
||||||
|
>(
|
||||||
|
cx: &Arc<Context>,
|
||||||
|
state: &State<T>,
|
||||||
|
encoder: E,
|
||||||
|
deps: &[&dyn HookDependency],
|
||||||
|
) {
|
||||||
|
use_effect(
|
||||||
|
{
|
||||||
|
let state = state.clone();
|
||||||
|
let cx = cx.clone();
|
||||||
|
move || {
|
||||||
|
cx.emit_event(&encoder(&state));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
deps,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user