|
| 1 | +use yew::prelude::*; |
| 2 | + |
| 3 | +use super::{use_throttle, use_unmount}; |
| 4 | + |
| 5 | +/// A hook that throttles calling effect callback, it is only called once every `millis`. |
| 6 | +/// |
| 7 | +/// # Example |
| 8 | +/// |
| 9 | +/// ```rust |
| 10 | +/// # use yew::prelude::*; |
| 11 | +/// # |
| 12 | +/// use yew_hooks::{use_throttle_effect, use_update}; |
| 13 | +/// |
| 14 | +/// #[function_component(ThrottleEffect)] |
| 15 | +/// fn throttle_effect() -> Html { |
| 16 | +/// let state = use_state(|| 0); |
| 17 | +/// let update = use_update(); |
| 18 | +/// |
| 19 | +/// { |
| 20 | +/// let state = state.clone(); |
| 21 | +/// use_throttle_effect( |
| 22 | +/// move || { |
| 23 | +/// state.set(*state + 1); |
| 24 | +/// }, |
| 25 | +/// 2000, |
| 26 | +/// ) |
| 27 | +/// }; |
| 28 | +/// |
| 29 | +/// let onclick = { Callback::from(move |_| update()) }; |
| 30 | +/// |
| 31 | +/// html! { |
| 32 | +/// <> |
| 33 | +/// <button {onclick}>{ "Click fast!" }</button> |
| 34 | +/// <b>{ "State: " }</b> {*state} |
| 35 | +/// </> |
| 36 | +/// } |
| 37 | +/// } |
| 38 | +/// ``` |
| 39 | +pub fn use_throttle_effect<Callback>(callback: Callback, millis: u32) |
| 40 | +where |
| 41 | + Callback: FnMut() + 'static, |
| 42 | +{ |
| 43 | + let throttle = use_throttle(callback, millis); |
| 44 | + |
| 45 | + { |
| 46 | + let throttle = throttle.clone(); |
| 47 | + use_effect(move || { |
| 48 | + throttle.run(); |
| 49 | + |
| 50 | + || () |
| 51 | + }); |
| 52 | + } |
| 53 | + |
| 54 | + use_unmount(move || { |
| 55 | + throttle.cancel(); |
| 56 | + }); |
| 57 | +} |
| 58 | + |
| 59 | +/// This hook is similar to [`use_throttle_effect`] but it accepts dependencies. |
| 60 | +/// |
| 61 | +/// Whenever the dependencies are changed, the throttle effect is run again. |
| 62 | +/// To detect changes, dependencies must implement `PartialEq`. |
| 63 | +pub fn use_throttle_effect_with_deps<Callback, Dependents>( |
| 64 | + callback: Callback, |
| 65 | + millis: u32, |
| 66 | + deps: Dependents, |
| 67 | +) where |
| 68 | + Callback: FnMut() + 'static, |
| 69 | + Dependents: PartialEq + 'static, |
| 70 | +{ |
| 71 | + let throttle = use_throttle(callback, millis); |
| 72 | + |
| 73 | + { |
| 74 | + let throttle = throttle.clone(); |
| 75 | + use_effect_with_deps( |
| 76 | + move |_| { |
| 77 | + throttle.run(); |
| 78 | + |
| 79 | + || () |
| 80 | + }, |
| 81 | + deps, |
| 82 | + ); |
| 83 | + } |
| 84 | + |
| 85 | + use_unmount(move || { |
| 86 | + throttle.cancel(); |
| 87 | + }); |
| 88 | +} |
0 commit comments