Improve inline docs * improve incorrect event handler return error message * Improve event handler docs * document the eval functions * document spawn and common spawn errors * fix event handler docs * add notes about how you use attributes and elements in rsx * add doc aliases for attributes and events we rename * add some more aliases for common search terms * don't doc ignore any public examples in core * don't ignore public doc examples in ssr * don't ignore examples in the dioxus package readme * add a warning when you launch without a renderer enabled * fix some outdated element docs * add a bunch of examples to resource * add notes about desktop events * add more docs for use_resource * add on_unimplemented hint to Dependency * fix some unresolved links * add examples to each of the router traits * add not implemented errors for router traits * add an example to the routable trait * expand rsx macro docs * improve memo docs * update the dioxus readme * mention dioxus crate features in the docs * fix a bunch of doc tests * fix html doc tests * fix router doc tests * fix dioxus signals doc tests * fix dioxus ssr doc tests * fix use_future example in the hooks cheat sheet * add a javascript alias for eval * fix hook explanation values * remove unused embed-doc-image dependency
27 lines
1.1 KiB
Rust
27 lines
1.1 KiB
Rust
use dioxus_core::{prelude::provide_root_context, prelude::try_consume_context, use_hook};
|
|
|
|
/// Try to get a value from the root of the virtual dom, if it doesn't exist, create a new one with the closure provided.
|
|
///
|
|
/// This is useful for global context inside of libraries. Instead of having the user provide context in the root of their app, you can use this hook to create a context at the root automatically.
|
|
///
|
|
/// # Example
|
|
/// ```rust
|
|
/// # #[derive(Clone)]
|
|
/// # struct Logger;
|
|
/// use dioxus::prelude::*;
|
|
///
|
|
/// fn use_logger() -> Logger {
|
|
/// // We want one logger per app in the root. Instead of forcing the user to always provide a logger, we can insert a default logger if one doesn't exist.
|
|
/// use_root_context(|| Logger)
|
|
/// }
|
|
/// ```
|
|
#[doc = include_str!("../docs/rules_of_hooks.md")]
|
|
#[doc = include_str!("../docs/moving_state_around.md")]
|
|
pub fn use_root_context<T: 'static + Clone>(new: impl FnOnce() -> T) -> T {
|
|
use_hook(|| {
|
|
try_consume_context::<T>()
|
|
// If no context is provided, create a new one at the root
|
|
.unwrap_or_else(|| provide_root_context(new()))
|
|
})
|
|
}
|