chore: finish tweaking context api

This commit is contained in:
Jonathan Kelley committed 2022-12-05 15:30:49 -08:00
1 parent 99a818996e
commit df4a1b6c7a
12 files changed
+76 -81

No files matched your search

+10 -5
View File
@@ -1,13 +1,18 @@
use dioxus_core::ScopeState;
use std::rc::Rc;
/// Consume some context in the tree
pub fn use_context<T: 'static>(cx: &ScopeState) -> Option<&T> {
cx.use_hook(|| cx.consume_context::<T>()).as_deref()
/// Consume some context in the tree, providing a sharable handle to the value
pub fn use_context<T: 'static + Clone>(cx: &ScopeState) -> Option<&T> {
cx.use_hook(|| cx.consume_context::<T>()).as_ref()
}
/// Provide some context via the tree and return a reference to it
///
/// Once the context has been provided, it is immutable. Mutations should be done via interior mutability.
pub fn use_context_provider<T: 'static>(cx: &ScopeState, f: impl FnOnce() -> T) -> &T {
cx.use_hook(|| cx.provide_context(f()))
pub fn use_context_provider<T: 'static + Clone>(cx: &ScopeState, f: impl FnOnce() -> T) -> &T {
cx.use_hook(|| {
let val = f();
cx.provide_context(val.clone());
val
})
}