diff --git a/examples/callback.rs b/examples/callback.rs new file mode 100644 index 000000000..f208bbcd7 --- /dev/null +++ b/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!" + } + }) +} diff --git a/examples/dog_app.rs b/examples/dog_app.rs index 8419cd04e..2b42a20fb 100644 --- a/examples/dog_app.rs +++ b/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" } }, } } diff --git a/packages/hooks/src/lib.rs b/packages/hooks/src/lib.rs index 1790eff1d..1332975ea 100644 --- a/packages/hooks/src/lib.rs +++ b/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::*; diff --git a/packages/hooks/src/usecallback.rs b/packages/hooks/src/usecallback.rs new file mode 100644 index 000000000..b46981879 --- /dev/null +++ b/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 + '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 { + // // + // }); +}