dioxus_core/global_context.rs
1use crate::runtime::RuntimeError;
2use crate::{
3 innerlude::SuspendedFuture, runtime::Runtime, CapturedError, Element, ScopeId, SuspenseContext,
4 Task,
5};
6use std::future::Future;
7use std::rc::Rc;
8use std::sync::Arc;
9
10/// Get the current scope id
11pub fn current_scope_id() -> Result<ScopeId, RuntimeError> {
12 Runtime::with(|rt| rt.current_scope_id().ok())
13 .ok()
14 .flatten()
15 .ok_or(RuntimeError::new())
16}
17
18#[doc(hidden)]
19/// Check if the virtual dom is currently inside of the body of a component
20pub fn vdom_is_rendering() -> bool {
21 Runtime::with(|rt| rt.rendering.get()).unwrap_or_default()
22}
23
24/// Throw a [`CapturedError`] into the current scope. The error will bubble up to the nearest [`crate::ErrorBoundary()`] or the root of the app.
25///
26/// # Examples
27/// ```rust, no_run
28/// # use dioxus::prelude::*;
29/// fn Component() -> Element {
30/// let request = spawn(async move {
31/// match reqwest::get("https://api.example.com").await {
32/// Ok(_) => unimplemented!(),
33/// // You can explicitly throw an error into a scope with throw_error
34/// Err(err) => ScopeId::APP.throw_error(err)
35/// }
36/// });
37///
38/// unimplemented!()
39/// }
40/// ```
41pub fn throw_error(error: impl Into<CapturedError> + 'static) {
42 current_scope_id()
43 .unwrap_or_else(|e| panic!("{}", e))
44 .throw_error(error)
45}
46
47/// Get the suspense context the current scope is in
48pub fn suspense_context() -> Option<SuspenseContext> {
49 current_scope_id()
50 .unwrap_or_else(|e| panic!("{}", e))
51 .suspense_context()
52}
53
54/// Consume context from the current scope
55pub fn try_consume_context<T: 'static + Clone>() -> Option<T> {
56 Runtime::with_current_scope(|cx| cx.consume_context::<T>())
57 .ok()
58 .flatten()
59}
60
61/// Consume context from the current scope
62pub fn consume_context<T: 'static + Clone>() -> T {
63 Runtime::with_current_scope(|cx| cx.consume_context::<T>())
64 .ok()
65 .flatten()
66 .unwrap_or_else(|| panic!("Could not find context {}", std::any::type_name::<T>()))
67}
68
69/// Consume context from the current scope
70pub fn consume_context_from_scope<T: 'static + Clone>(scope_id: ScopeId) -> Option<T> {
71 Runtime::with(|rt| {
72 rt.get_state(scope_id)
73 .and_then(|cx| cx.consume_context::<T>())
74 })
75 .ok()
76 .flatten()
77}
78
79/// Check if the current scope has a context
80pub fn has_context<T: 'static + Clone>() -> Option<T> {
81 Runtime::with_current_scope(|cx| cx.has_context::<T>())
82 .ok()
83 .flatten()
84}
85
86/// Provide context to the current scope
87pub fn provide_context<T: 'static + Clone>(value: T) -> T {
88 Runtime::with_current_scope(|cx| cx.provide_context(value)).unwrap()
89}
90
91/// Provide a context to the root scope
92pub fn provide_root_context<T: 'static + Clone>(value: T) -> T {
93 Runtime::with_current_scope(|cx| cx.provide_root_context(value)).unwrap()
94}
95
96/// Suspended the current component on a specific task and then return None
97pub fn suspend(task: Task) -> Element {
98 Err(crate::innerlude::RenderError::Suspended(
99 SuspendedFuture::new(task),
100 ))
101}
102
103/// Start a new future on the same thread as the rest of the VirtualDom.
104///
105/// **You should generally use `spawn` instead of this method unless you specifically need to run a task during suspense**
106///
107/// This future will not contribute to suspense resolving but it will run during suspense.
108///
109/// Because this future runs during suspense, you need to be careful to work with hydration. It is not recommended to do any async IO work in this future, as it can easily cause hydration issues. However, you can use isomorphic tasks to do work that can be consistently replicated on the server and client like logging or responding to state changes.
110///
111/// ```rust, no_run
112/// # use dioxus::prelude::*;
113/// # use dioxus_core::spawn_isomorphic;
114/// // ❌ Do not do requests in isomorphic tasks. It may resolve at a different time on the server and client, causing hydration issues.
115/// let mut state = use_signal(|| None);
116/// spawn_isomorphic(async move {
117/// state.set(Some(reqwest::get("https://api.example.com").await));
118/// });
119///
120/// // ✅ You may wait for a signal to change and then log it
121/// let mut state = use_signal(|| 0);
122/// spawn_isomorphic(async move {
123/// loop {
124/// tokio::time::sleep(std::time::Duration::from_secs(1)).await;
125/// println!("State is {state}");
126/// }
127/// });
128/// ```
129///
130#[doc = include_str!("../docs/common_spawn_errors.md")]
131pub fn spawn_isomorphic(fut: impl Future<Output = ()> + 'static) -> Task {
132 Runtime::with_current_scope(|cx| cx.spawn_isomorphic(fut)).unwrap()
133}
134
135/// Spawns the future and returns the [`Task`]. This task will automatically be canceled when the component is dropped.
136///
137/// # Example
138/// ```rust
139/// use dioxus::prelude::*;
140///
141/// fn App() -> Element {
142/// rsx! {
143/// button {
144/// onclick: move |_| {
145/// spawn(async move {
146/// tokio::time::sleep(std::time::Duration::from_secs(1)).await;
147/// println!("Hello World");
148/// });
149/// },
150/// "Print hello in one second"
151/// }
152/// }
153/// }
154/// ```
155///
156#[doc = include_str!("../docs/common_spawn_errors.md")]
157pub fn spawn(fut: impl Future<Output = ()> + 'static) -> Task {
158 Runtime::with_current_scope(|cx| cx.spawn(fut)).unwrap()
159}
160
161/// Queue an effect to run after the next render. You generally shouldn't need to interact with this function directly. [use_effect](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_effect.html) will call this function for you.
162pub fn queue_effect(f: impl FnOnce() + 'static) {
163 Runtime::with_current_scope(|cx| cx.queue_effect(f)).unwrap()
164}
165
166/// Spawn a future that Dioxus won't clean up when this component is unmounted
167///
168/// This is good for tasks that need to be run after the component has been dropped.
169///
170/// **This will run the task in the root scope. Any calls to global methods inside the future (including `context`) will be run in the root scope.**
171///
172/// # Example
173///
174/// ```rust
175/// use dioxus::prelude::*;
176/// use dioxus_core::spawn_forever;
177///
178/// // The parent component can create and destroy children dynamically
179/// fn App() -> Element {
180/// let mut count = use_signal(|| 0);
181///
182/// rsx! {
183/// button {
184/// onclick: move |_| count += 1,
185/// "Increment"
186/// }
187/// button {
188/// onclick: move |_| count -= 1,
189/// "Decrement"
190/// }
191///
192/// for id in 0..10 {
193/// Child { id }
194/// }
195/// }
196/// }
197///
198/// #[component]
199/// fn Child(id: i32) -> Element {
200/// rsx! {
201/// button {
202/// onclick: move |_| {
203/// // This will spawn a task in the root scope that will run forever
204/// // It will keep running even if you drop the child component by decreasing the count
205/// spawn_forever(async move {
206/// loop {
207/// tokio::time::sleep(std::time::Duration::from_secs(1)).await;
208/// println!("Running task spawned in child component {id}");
209/// }
210/// });
211/// },
212/// "Spawn background task"
213/// }
214/// }
215/// }
216/// ```
217///
218#[doc = include_str!("../docs/common_spawn_errors.md")]
219pub fn spawn_forever(fut: impl Future<Output = ()> + 'static) -> Option<Task> {
220 Runtime::with_scope(ScopeId::ROOT, |cx| cx.spawn(fut)).ok()
221}
222
223/// Informs the scheduler that this task is no longer needed and should be removed.
224///
225/// This drops the task immediately.
226pub fn remove_future(id: Task) {
227 Runtime::with(|rt| rt.remove_task(id)).expect("Runtime to exist");
228}
229
230/// Store a value between renders. The foundational hook for all other hooks.
231///
232/// Accepts an `initializer` closure, which is run on the first use of the hook (typically the initial render).
233/// `use_hook` will return a clone of the value on every render.
234///
235/// In order to clean up resources you would need to implement the [`Drop`] trait for an inner value stored in a RC or similar (Signals for instance),
236/// as these only drop their inner value once all references have been dropped, which only happens when the component is dropped.
237///
238/// <div class="warning">
239///
240/// `use_hook` is not reactive. It just returns the value on every render. If you need state that will track changes, use [`use_signal`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_signal.html) instead.
241///
242/// ❌ Don't use `use_hook` with `Rc<RefCell<T>>` for state. It will not update the UI and other hooks when the state changes.
243/// ```rust
244/// use dioxus::prelude::*;
245/// use std::rc::Rc;
246/// use std::cell::RefCell;
247///
248/// pub fn Comp() -> Element {
249/// let count = use_hook(|| Rc::new(RefCell::new(0)));
250///
251/// rsx! {
252/// button {
253/// onclick: move |_| *count.borrow_mut() += 1,
254/// "{count.borrow()}"
255/// }
256/// }
257/// }
258/// ```
259///
260/// ✅ Use `use_signal` instead.
261/// ```rust
262/// use dioxus::prelude::*;
263///
264/// pub fn Comp() -> Element {
265/// let mut count = use_signal(|| 0);
266///
267/// rsx! {
268/// button {
269/// onclick: move |_| count += 1,
270/// "{count}"
271/// }
272/// }
273/// }
274/// ```
275///
276/// </div>
277///
278/// # Example
279///
280/// ```rust, no_run
281/// use dioxus::prelude::*;
282///
283/// // prints a greeting on the initial render
284/// pub fn use_hello_world() {
285/// use_hook(|| println!("Hello, world!"));
286/// }
287/// ```
288///
289/// # Custom Hook Example
290///
291/// ```rust, no_run
292/// use dioxus::prelude::*;
293///
294/// pub struct InnerCustomState(usize);
295///
296/// impl Drop for InnerCustomState {
297/// fn drop(&mut self){
298/// println!("Component has been dropped.");
299/// }
300/// }
301///
302/// #[derive(Clone, Copy)]
303/// pub struct CustomState {
304/// inner: Signal<InnerCustomState>
305/// }
306///
307/// pub fn use_custom_state() -> CustomState {
308/// use_hook(|| CustomState {
309/// inner: Signal::new(InnerCustomState(0))
310/// })
311/// }
312/// ```
313#[track_caller]
314pub fn use_hook<State: Clone + 'static>(initializer: impl FnOnce() -> State) -> State {
315 Runtime::with_current_scope(|cx| cx.use_hook(initializer)).unwrap()
316}
317
318/// Get the current render since the inception of this component.
319///
320/// This can be used as a helpful diagnostic when debugging hooks/renders, etc.
321pub fn generation() -> usize {
322 Runtime::with_current_scope(|cx| cx.generation()).unwrap()
323}
324
325/// Get the parent of the current scope if it exists.
326pub fn parent_scope() -> Option<ScopeId> {
327 Runtime::with_current_scope(|cx| cx.parent_id())
328 .ok()
329 .flatten()
330}
331
332/// Mark the current scope as dirty, causing it to re-render.
333pub fn needs_update() {
334 let _ = Runtime::with_current_scope(|cx| cx.needs_update());
335}
336
337/// Mark the current scope as dirty, causing it to re-render.
338pub fn needs_update_any(id: ScopeId) {
339 let _ = Runtime::with_current_scope(|cx| cx.needs_update_any(id));
340}
341
342/// Schedule an update for the current component.
343///
344/// Note: Unlike [`needs_update`], the function returned by this method will work outside of the dioxus runtime.
345///
346/// Note: The function returned by this method will schedule an update for the current component even if it has already updated between when `schedule_update` was called and when the returned function is called.
347/// If the desired behavior is to invalidate the current rendering of the current component (and no-op if already invalidated)
348/// [`subscribe`](crate::reactive_context::ReactiveContext::subscribe) to the [`current`](crate::reactive_context::ReactiveContext::current) [`ReactiveContext`](crate::reactive_context::ReactiveContext) instead.
349///
350/// You should prefer [`schedule_update_any`] if you need to update multiple components.
351#[track_caller]
352pub fn schedule_update() -> Arc<dyn Fn() + Send + Sync> {
353 Runtime::with_current_scope(|cx| cx.schedule_update()).unwrap_or_else(|e| panic!("{}", e))
354}
355
356/// Schedule an update for any component given its [`ScopeId`].
357///
358/// A component's [`ScopeId`] can be obtained from the [`current_scope_id`] method.
359///
360/// Note: Unlike [`needs_update`], the function returned by this method will work outside of the dioxus runtime.
361///
362/// Note: It does not matter when `schedule_update_any` is called: the returned function will invalidate what ever generation of the specified component is current when returned function is called.
363/// If the desired behavior is to schedule invalidation of the current rendering of a component, use [`ReactiveContext`](crate::reactive_context::ReactiveContext) instead.
364#[track_caller]
365pub fn schedule_update_any() -> Arc<dyn Fn(ScopeId) + Send + Sync> {
366 Runtime::with_current_scope(|cx| cx.schedule_update_any()).unwrap_or_else(|e| panic!("{}", e))
367}
368
369/// Creates a callback that will be run before the component is removed.
370/// This can be used to clean up side effects from the component
371/// (created with [`use_effect`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_effect.html)).
372///
373/// Note:
374/// Effects do not run on the server, but use_drop **DOES**. It runs any time the component is dropped including during SSR rendering on the server. If your clean up logic targets web, the logic has to be gated by a feature, see the below example for details.
375///
376/// Example:
377/// ```rust
378/// use dioxus::prelude::*;
379/// use dioxus_core::use_drop;
380///
381/// fn app() -> Element {
382/// let mut state = use_signal(|| true);
383/// rsx! {
384/// for _ in 0..100 {
385/// h1 {
386/// "spacer"
387/// }
388/// }
389/// if state() {
390/// child_component {}
391/// }
392/// button {
393/// onclick: move |_| {
394/// state.toggle()
395/// },
396/// "Unmount element"
397/// }
398/// }
399/// }
400///
401/// fn child_component() -> Element {
402/// let mut original_scroll_position = use_signal(|| 0.0);
403///
404/// use_effect(move || {
405/// let window = web_sys::window().unwrap();
406/// let document = window.document().unwrap();
407/// let element = document.get_element_by_id("my_element").unwrap();
408/// element.scroll_into_view();
409/// original_scroll_position.set(window.scroll_y().unwrap());
410/// });
411///
412/// use_drop(move || {
413/// // This only make sense to web and hence the `web!` macro
414/// web! {
415/// /// restore scroll to the top of the page
416/// let window = web_sys::window().unwrap();
417/// window.scroll_with_x_and_y(original_scroll_position(), 0.0);
418/// }
419/// });
420///
421/// rsx! {
422/// div {
423/// id: "my_element",
424/// "hello"
425/// }
426/// }
427/// }
428/// ```
429#[doc(alias = "use_on_unmount")]
430pub fn use_drop<D: FnOnce() + 'static>(destroy: D) {
431 struct LifeCycle<D: FnOnce()> {
432 /// Wrap the closure in an option so that we can take it out on drop.
433 ondestroy: Option<D>,
434 }
435
436 /// On drop, we want to run the closure.
437 impl<D: FnOnce()> Drop for LifeCycle<D> {
438 fn drop(&mut self) {
439 if let Some(f) = self.ondestroy.take() {
440 f();
441 }
442 }
443 }
444
445 use_hook(|| {
446 Rc::new(LifeCycle {
447 ondestroy: Some(destroy),
448 })
449 });
450}
451
452/// A hook that allows you to insert a "before render" function.
453///
454/// This function will always be called before dioxus tries to render your component. This should be used for safely handling
455/// early returns
456pub fn use_before_render(f: impl FnMut() + 'static) {
457 use_hook(|| before_render(f));
458}
459
460/// Push this function to be run after the next render
461///
462/// This function will always be called before dioxus tries to render your component. This should be used for safely handling
463/// early returns
464pub fn use_after_render(f: impl FnMut() + 'static) {
465 use_hook(|| after_render(f));
466}
467
468/// Push a function to be run before the next render
469/// This is a hook and will always run, so you can't unschedule it
470/// Will run for every progression of suspense, though this might change in the future
471pub fn before_render(f: impl FnMut() + 'static) {
472 let _ = Runtime::with_current_scope(|cx| cx.push_before_render(f));
473}
474
475/// Push a function to be run after the render is complete, even if it didn't complete successfully
476pub fn after_render(f: impl FnMut() + 'static) {
477 let _ = Runtime::with_current_scope(|cx| cx.push_after_render(f));
478}
479
480/// Use a hook with a cleanup function
481pub fn use_hook_with_cleanup<T: Clone + 'static>(
482 hook: impl FnOnce() -> T,
483 cleanup: impl FnOnce(T) + 'static,
484) -> T {
485 let value = use_hook(hook);
486 let _value = value.clone();
487 use_drop(move || cleanup(_value));
488 value
489}
490
491/// Force every component to be dirty and require a re-render. Used by hot-reloading.
492///
493/// This might need to change to a different flag in the event hooks order changes within components.
494/// What we really need is a way to mark components as needing a complete rebuild if they were hit by changes.
495pub fn force_all_dirty() {
496 Runtime::with(|rt| {
497 rt.scope_states.borrow_mut().iter().for_each(|state| {
498 if let Some(scope) = state.as_ref() {
499 scope.needs_update();
500 }
501 });
502 })
503 .expect("Runtime to exist");
504}