From 4ad4b18e4bcfc57aa487f11b45c38d516c93b2d7 Mon Sep 17 00:00:00 2001 From: Jonathan Kelley Date: Sat, 26 Feb 2022 17:31:35 -0500 Subject: [PATCH] feat: useeffect --- packages/hooks/src/useeffect.rs | 43 +++++++++++++++++++++------------ 1 file changed, 27 insertions(+), 16 deletions(-) diff --git a/packages/hooks/src/useeffect.rs b/packages/hooks/src/useeffect.rs index b6f6a01eb..09366fc35 100644 --- a/packages/hooks/src/useeffect.rs +++ b/packages/hooks/src/useeffect.rs @@ -10,20 +10,39 @@ use crate::UseFutureDep; /// will be allowed to continue /// /// - dependencies: a tuple of references to values that are PartialEq + Clone -pub fn use_effect<'a, T: 'static, F: Future + 'static, D: UseFutureDep>( - cx: &'a ScopeState, - dependencies: D, - future: impl FnOnce(D::Out) -> F, -) -> &'a UseEffect { +/// +/// ## Examples +/// +/// ```rust, ignore +/// +/// #[inline_props] +/// fn app(cx: Scope, name: &str) -> Element { +/// use_effect(&cx, (name,), |(name,)| async move { +/// set_title(name); +/// })) +/// } +/// ``` +pub fn use_effect(cx: &ScopeState, dependencies: D, future: impl FnOnce(D::Out) -> F) +where + T: 'static, + F: Future + 'static, + D: UseFutureDep, +{ + struct UseEffect { + needs_regen: bool, + task: Cell>, + dependencies: Vec>, + } + let state = cx.use_hook(move |_| UseEffect { - needs_regen: Cell::new(true), + needs_regen: true, task: Cell::new(None), dependencies: Vec::new(), }); - if dependencies.clone().apply(&mut state.dependencies) || state.needs_regen.get() { + if dependencies.clone().apply(&mut state.dependencies) || state.needs_regen { // We don't need regen anymore - state.needs_regen.set(false); + state.needs_regen = false; // Create the new future let fut = future(dependencies.out()); @@ -32,14 +51,6 @@ pub fn use_effect<'a, T: 'static, F: Future + 'static, D: UseFutureD fut.await; }))); } - - state -} - -pub struct UseEffect { - needs_regen: Cell, - task: Cell>, - dependencies: Vec>, } #[cfg(test)]