dioxus/packages/hooks/src/useref.rs

58 lines
1.3 KiB
Rust
Raw Normal View History

use std::{
2022-01-07 16:51:25 +00:00
cell::{Ref, RefCell, RefMut},
rc::Rc,
};
2021-09-21 16:11:04 +00:00
use dioxus_core::ScopeState;
2021-09-21 16:11:04 +00:00
pub fn use_ref<'a, T: 'static>(cx: &'a ScopeState, f: impl FnOnce() -> T) -> &'a UseRef<T> {
2022-01-08 14:32:53 +00:00
cx.use_hook(|_| UseRef {
update_callback: cx.schedule_update(),
value: Rc::new(RefCell::new(f())),
2022-01-08 14:32:53 +00:00
})
}
pub struct UseRef<T> {
update_callback: Rc<dyn Fn()>,
value: Rc<RefCell<T>>,
2021-09-21 16:11:04 +00:00
}
impl<T> UseRef<T> {
2021-09-21 16:11:04 +00:00
pub fn read(&self) -> Ref<'_, T> {
self.value.borrow()
2021-09-21 16:11:04 +00:00
}
2021-11-19 05:49:04 +00:00
pub fn set(&self, new: T) {
*self.value.borrow_mut() = new;
2021-11-19 05:49:04 +00:00
self.needs_update();
}
2021-09-21 16:11:04 +00:00
pub fn read_write(&self) -> (Ref<'_, T>, &Self) {
(self.read(), self)
}
/// Calling "write" will force the component to re-render
pub fn write(&self) -> RefMut<'_, T> {
self.needs_update();
self.value.borrow_mut()
2021-09-21 16:11:04 +00:00
}
/// Allows the ability to write the value without forcing a re-render
pub fn write_silent(&self) -> RefMut<'_, T> {
self.value.borrow_mut()
}
pub fn needs_update(&self) {
(self.update_callback)();
2021-09-21 16:11:04 +00:00
}
}
impl<T> Clone for UseRef<T> {
2021-09-21 16:11:04 +00:00
fn clone(&self) -> Self {
Self {
update_callback: self.update_callback.clone(),
value: self.value.clone(),
}
2021-09-21 16:11:04 +00:00
}
}