From 45473ece8c2fb9ac076b4e881f071d0efd7b9a1e Mon Sep 17 00:00:00 2001 From: Jonathan Kelley Date: Sat, 19 Feb 2022 18:00:03 -0500 Subject: [PATCH] feat: add some helpers to use_ref --- examples/use_ref.rs | 21 +++++++++++++++++++++ packages/hooks/src/useref.rs | 11 +++++++++++ 2 files changed, 32 insertions(+) create mode 100644 examples/use_ref.rs diff --git a/examples/use_ref.rs b/examples/use_ref.rs new file mode 100644 index 000000000..358b9c266 --- /dev/null +++ b/examples/use_ref.rs @@ -0,0 +1,21 @@ +use std::collections::HashMap; + +use dioxus::prelude::*; +fn main() {} + +fn app(cx: Scope) -> Element { + let val = use_ref(&cx, || HashMap::::new()); + + // Pull the value out locally + let p = val.read(); + + // to get an &HashMap we have to "reborrow" through the RefCell + // Be careful: passing this into children might cause a double borrow of the RefCell and a panic + let g = &*p; + + cx.render(rsx! { + div { + "hi" + } + }) +} diff --git a/packages/hooks/src/useref.rs b/packages/hooks/src/useref.rs index 3ddf86e8c..a0b9189d0 100644 --- a/packages/hooks/src/useref.rs +++ b/packages/hooks/src/useref.rs @@ -42,6 +42,17 @@ impl UseRef { self.value.borrow_mut() } + /// Take a reference to the inner value termporarily and produce a new value + pub fn with(&self, f: impl FnOnce(&T) -> O) -> O { + f(&*self.read()) + } + + /// Take a reference to the inner value termporarily and produce a new value, + /// modifying the original in place. + pub fn with_mut(&self, f: impl FnOnce(&mut T) -> O) -> O { + f(&mut *self.write()) + } + pub fn needs_update(&self) { (self.update_callback)(); }