1
0
Эх сурвалжийг харах

wip: add use_callback hook

Jonathan Kelley 2 жил өмнө
parent
commit
57c10174ec

+ 20 - 0
examples/callback.rs

@@ -0,0 +1,20 @@
+use std::rc::Rc;
+
+use dioxus::prelude::*;
+
+fn main() {
+    dioxus_desktop::launch(app);
+}
+
+fn app(cx: Scope) -> Element {
+    let login = use_callback!(cx, || |evt| async {
+        //
+    });
+
+    cx.render(rsx! {
+        button {
+            onclick: login,
+            "Click me!"
+        }
+    })
+}

+ 4 - 4
examples/dog_app.rs

@@ -1,5 +1,5 @@
 use dioxus::prelude::*;
-use std::collections::HashMap;
+use std::{collections::HashMap, marker::PhantomData};
 
 fn main() {
     dioxus_desktop::launch(|cx| {
@@ -65,7 +65,7 @@ async fn breed_pic(cx: Scope, breed: String) -> Element {
     });
 
     match fut.await {
-        Ok(resp) => cx.render(rsx! {
+        Ok(resp) => render! {
             div {
                 button {
                     onclick: move |_| fut.restart(),
@@ -77,7 +77,7 @@ async fn breed_pic(cx: Scope, breed: String) -> Element {
                     max_height: "500px",
                 }
             }
-        }),
-        Err(_) => cx.render(rsx! { div { "loading dogs failed" } }),
+        },
+        Err(_) => render! { div { "loading dogs failed" } },
     }
 }

+ 2 - 2
packages/hooks/src/lib.rs

@@ -19,5 +19,5 @@ pub use usefuture::*;
 mod useeffect;
 pub use useeffect::*;
 
-// mod usesuspense;
-// pub use usesuspense::*;
+mod usecallback;
+pub use usecallback::*;

+ 36 - 0
packages/hooks/src/usecallback.rs

@@ -0,0 +1,36 @@
+use std::rc::Rc;
+
+use dioxus_core::{prelude::EventHandler, ScopeState};
+use std::future::Future;
+
+#[macro_export]
+macro_rules! use_callback {
+    ($cx:ident, || || $($rest:tt)*) => { use_callback( $cx, (), |_| $($rest)* ) };
+    ($cx:ident, || |$myarg:ident| $($rest:tt)*) => {
+        use_callback(
+            $cx,
+            || |$myarg| async {}
+        )
+    };
+}
+pub fn use_callback<'a, T, R, F>(cx: &'a ScopeState, make: impl FnOnce() -> R) -> impl FnMut(T) + 'a
+where
+    R: FnMut(T) -> F + 'static,
+    F: Future<Output = ()> + 'static,
+{
+    let mut hook = make();
+
+    move |evt| cx.spawn(hook(evt))
+}
+
+fn it_works(cx: &ScopeState) {
+    let p = use_callback(cx, || {
+        |()| async {
+            //
+        }
+    });
+
+    // let p = use_callback!(cx, || |evt| async {
+    //     //
+    // });
+}