fix: usestate modify panic

This commit is contained in:
Jonathan Kelley committed 2022-01-31 14:33:25 -05:00
1 parent 120ee18368
commit fb75948363
1 file changed
+5 -2
+5 -2
View File
@@ -39,6 +39,7 @@ pub fn use_state<'a, T: 'static>(
let setter = Rc::new({ let setter = Rc::new({
crate::to_owned![update_callback, slot]; crate::to_owned![update_callback, slot];
move |new| { move |new| {
{
let mut slot = slot.borrow_mut(); let mut slot = slot.borrow_mut();
// if there's only one reference (weak or otherwise), we can just swap the values // if there's only one reference (weak or otherwise), we can just swap the values
@@ -48,7 +49,7 @@ pub fn use_state<'a, T: 'static>(
} else { } else {
*slot = Rc::new(new); *slot = Rc::new(new);
} }
}
update_callback(); update_callback();
} }
}); });
@@ -153,8 +154,10 @@ impl<T: 'static> UseState<T> {
/// } /// }
/// ``` /// ```
pub fn modify(&self, f: impl FnOnce(&T) -> T) { pub fn modify(&self, f: impl FnOnce(&T) -> T) {
let new_val = {
let current = self.slot.borrow(); let current = self.slot.borrow();
let new_val = f(current.as_ref()); f(current.as_ref())
};
(self.setter)(new_val); (self.setter)(new_val);
} }