From 458c13fb7424be424271b4ee0b6d7a7e5d95bd0b Mon Sep 17 00:00:00 2001 From: Evan Almloff Date: Wed, 24 Jan 2024 18:34:22 -0600 Subject: [PATCH] run effects in the scope they were created in --- packages/core/src/scope_context.rs | 6 ++++-- packages/signals/src/effect.rs | 8 +++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/core/src/scope_context.rs b/packages/core/src/scope_context.rs index ea3a63134..f3e4a87bf 100644 --- a/packages/core/src/scope_context.rs +++ b/packages/core/src/scope_context.rs @@ -231,7 +231,7 @@ impl ScopeContext { /// This is good for tasks that need to be run after the component has been dropped. pub fn spawn_forever(&self, fut: impl Future + 'static) -> Task { // The root scope will never be unmounted so we can just add the task at the top of the app - Runtime::with(|rt| rt.spawn(ScopeId::ROOT, fut)).expect("Runtime to exist") + Runtime::with(|rt| rt.spawn(self.id, fut)).expect("Runtime to exist") } /// Informs the scheduler that this task is no longer needed and should be removed. @@ -386,6 +386,8 @@ impl ScopeId { /// Run a closure inside of scope's runtime pub fn in_runtime(self, f: impl FnOnce() -> T) -> T { - Runtime::with_scope(self, |_| f()).expect("to be in a dioxus runtime") + Runtime::current() + .expect("to be in a dioxus runtime") + .on_scope(self, f) } } diff --git a/packages/signals/src/effect.rs b/packages/signals/src/effect.rs index 57a34fd29..0d5b4c2cf 100644 --- a/packages/signals/src/effect.rs +++ b/packages/signals/src/effect.rs @@ -126,10 +126,12 @@ impl Effect { /// Create a new effect. The effect will be run immediately and whenever any signal it reads changes. /// /// The signal will be owned by the current component and will be dropped when the component is dropped. - pub fn new(callback: impl FnMut() + 'static) -> Self { + pub fn new(mut callback: impl FnMut() + 'static) -> Self { + let source = current_scope_id().expect("in a virtual dom"); let myself = Self { - source: current_scope_id().expect("in a virtual dom"), - inner: EffectInner::new(Box::new(callback)), + source, + #[allow(clippy::redundant_closure)] + inner: EffectInner::new(Box::new(move || source.in_runtime(|| callback()))), }; EFFECT_STACK.with(|stack| {