Improved state mangement
This commit is contained in:
+12
-1
@@ -30,6 +30,17 @@ fn main() {
|
||||
|
||||
fn app(cx: &Arc<Context>) -> Vec<Node> {
|
||||
let count = use_state(0);
|
||||
let count2 = use_state(0);
|
||||
|
||||
use_effect(
|
||||
{
|
||||
let count2 = count2.clone();
|
||||
move || {
|
||||
*count2.get() += 1;
|
||||
}
|
||||
},
|
||||
&[&count],
|
||||
);
|
||||
|
||||
cx.on_event({
|
||||
let count = count.clone();
|
||||
@@ -40,5 +51,5 @@ fn app(cx: &Arc<Context>) -> Vec<Node> {
|
||||
}
|
||||
});
|
||||
|
||||
vec![Node::String(Arc::new(move || format!("{count}")))]
|
||||
vec![Node::String(Arc::new(move || format!("{count} {count2}")))]
|
||||
}
|
||||
|
||||
+19
-1
@@ -5,7 +5,7 @@ use std::{
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HookEffect(Arc<Mutex<dyn Fn() + Send + Sync>>);
|
||||
pub struct HookEffect(Arc<Mutex<dyn FnMut() + Send + Sync>>);
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct State<T> {
|
||||
@@ -101,3 +101,21 @@ impl<T> DerefMut for Inner<'_, T> {
|
||||
&mut self.value
|
||||
}
|
||||
}
|
||||
|
||||
pub trait HookDependency {
|
||||
fn on_update(&self, hook: HookEffect);
|
||||
}
|
||||
|
||||
impl<T> HookDependency for State<T> {
|
||||
fn on_update(&self, hook: HookEffect) {
|
||||
self.dependents.lock().unwrap().push(hook);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn use_effect<F: FnMut() + Send + Sync + 'static>(f: F, dependencies: &[&dyn HookDependency]) {
|
||||
let hook = HookEffect(Arc::new(Mutex::new(f)));
|
||||
|
||||
for d in dependencies {
|
||||
d.on_update(hook.clone());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user