Skip to content

Commit

Permalink
Allow to consume deps in use_callback
Browse files Browse the repository at this point in the history
  • Loading branch information
jetli committed Apr 15, 2022
1 parent d2c3685 commit 7e9951d
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 9 deletions.
24 changes: 19 additions & 5 deletions packages/yew/src/functional/hooks/use_callback.rs
@@ -1,3 +1,5 @@
use std::rc::Rc;

use crate::callback::Callback;
use crate::functional::{hook, use_memo};

Expand Down Expand Up @@ -37,15 +39,17 @@ use crate::functional::{hook, use_memo};
/// // This callback depends on (), so it's created only once, then MyComponent
/// // will be rendered only once even when you click the button mutiple times.
/// let callback = use_callback(
/// move |name| format!("Hello, {}!", name),
/// move |name, _| format!("Hello, {}!", name),
/// ()
/// );
///
/// // It can also be used for events.
/// // It can also be used for events, this callback depends on `counter`.
/// let oncallback = {
/// let counter = counter.clone();
/// use_callback(
/// move |_e| (),
/// move |_e, counter| {
/// let _ = **counter;
/// },
/// counter
/// )
/// };
Expand All @@ -68,8 +72,18 @@ pub fn use_callback<IN, OUT, F, D>(f: F, deps: D) -> Callback<IN, OUT>
where
IN: 'static,
OUT: 'static,
F: Fn(IN) -> OUT + 'static,
F: Fn(IN, &D) -> OUT + 'static,
D: PartialEq + 'static,
{
(*use_memo(move |_| Callback::from(f), deps)).clone()
let deps = Rc::new(deps);

(*use_memo(
move |deps| {
let deps = deps.clone();
let f = move |value: IN| f(value, deps.as_ref());
Callback::from(f)
},
deps,
))
.clone()
}
2 changes: 1 addition & 1 deletion packages/yew/tests/use_callback.rs
Expand Up @@ -42,7 +42,7 @@ async fn use_callback_works() {
fn use_callback_comp() -> Html {
let state = use_state(|| 0);

let callback = use_callback(move |name| format!("Hello, {}!", name), ());
let callback = use_callback(move |name, _| format!("Hello, {}!", name), ());

use_effect(move || {
if *state < 5 {
Expand Down
Expand Up @@ -37,15 +37,17 @@ fn callback() -> Html {
// This callback depends on (), so it's created only once, then MyComponent
// will be rendered only once even when you click the button mutiple times.
let callback = use_callback(
move |name| format!("Hello, {}!", name),
move |name, _| format!("Hello, {}!", name),
()
);

// It can also be used for events.
// It can also be used for events, this callback depends on `counter`.
let oncallback = {
let counter = counter.clone();
use_callback(
move |_e| (),
move |_e, counter| {
let _ = **counter;
},
counter
)
};
Expand Down

0 comments on commit 7e9951d

Please sign in to comment.