feat: add update functionality to useref

This commit is contained in:
Jonathan Kelley committed 2021-10-04 10:22:20 -04:00
1 parent 5502429626
commit a2b0c50a34
16 files changed
+77 -47

No files matched your search

+36 -9
View File
@@ -1,14 +1,37 @@
use std::cell::{Ref, RefCell, RefMut};
use std::{
cell::{Cell, Ref, RefCell, RefMut},
rc::Rc,
};
use dioxus_core::Context;
pub fn use_ref<T: 'static>(cx: Context, f: impl FnOnce() -> T) -> UseRef<T> {
cx.use_hook(
|_| UseRefInner {
update_scheuled: Cell::new(false),
update_callback: cx.schedule_update(),
value: RefCell::new(f()),
},
|inner| {
inner.update_scheuled.set(false);
UseRef { inner }
},
|_| {},
)
}
pub struct UseRef<'a, T> {
inner: &'a RefCell<T>,
inner: &'a UseRefInner<T>,
}
struct UseRefInner<T> {
update_scheuled: Cell<bool>,
update_callback: Rc<dyn Fn()>,
value: RefCell<T>,
}
impl<'a, T> UseRef<'a, T> {
pub fn read(&self) -> Ref<'_, T> {
self.inner.borrow()
self.inner.value.borrow()
}
pub fn read_write(&self) -> (Ref<'_, T>, &Self) {
@@ -17,12 +40,20 @@ impl<'a, T> UseRef<'a, T> {
/// Calling "write" will force the component to re-render
pub fn write(&self) -> RefMut<'_, T> {
self.inner.borrow_mut()
self.needs_update();
self.inner.value.borrow_mut()
}
/// Allows the ability to write the value without forcing a re-render
pub fn write_silent(&self) -> RefMut<'_, T> {
self.inner.borrow_mut()
self.inner.value.borrow_mut()
}
pub fn needs_update(&self) {
if !self.inner.update_scheuled.get() {
self.inner.update_scheuled.set(true);
(self.inner.update_callback)();
}
}
}
@@ -32,7 +63,3 @@ impl<T> Clone for UseRef<'_, T> {
}
}
impl<T> Copy for UseRef<'_, T> {}
pub fn use_ref<T: 'static>(cx: Context, f: impl FnOnce() -> T) -> UseRef<T> {
cx.use_hook(|_| RefCell::new(f()), |f| UseRef { inner: f }, |_| {})
}