use crate::context::ContextHandle;
use crate::functional::{get_current_scope, use_hook};
pub fn use_context<T: Clone + PartialEq + 'static>() -> Option<T> {
struct UseContextState<T2: Clone + PartialEq + 'static> {
initialized: bool,
context: Option<(T2, ContextHandle<T2>)>,
}
let scope = get_current_scope()
.expect("No current Scope. `use_context` can only be called inside function components");
use_hook(
move || UseContextState {
initialized: false,
context: None,
},
|state: &mut UseContextState<T>, updater| {
if !state.initialized {
state.initialized = true;
let callback = move |ctx: T| {
updater.callback(|state: &mut UseContextState<T>| {
if let Some(context) = &mut state.context {
context.0 = ctx;
}
true
});
};
state.context = scope.context::<T>(callback.into());
}
Some(state.context.as_ref()?.0.clone())
},
|state| {
state.context = None;
},
)
}