Skip to content

Commit

Permalink
fix: try_update() and try_set() on Resource should not panic (c…
Browse files Browse the repository at this point in the history
…loses #1915) (#1916)
  • Loading branch information
gbj authored Oct 19, 2023
1 parent 319017f commit 4a83ffc
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 10 deletions.
8 changes: 5 additions & 3 deletions leptos_reactive/src/resource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -685,7 +685,7 @@ impl<S, T> SignalUpdate for Resource<S, T> {
#[inline(always)]
fn try_update<O>(&self, f: impl FnOnce(&mut Option<T>) -> O) -> Option<O> {
with_runtime(|runtime| {
runtime.resource(self.id, |resource: &ResourceState<S, T>| {
runtime.try_resource(self.id, |resource: &ResourceState<S, T>| {
if resource.loading.get_untracked() {
resource.version.set(resource.version.get() + 1);
for suspense_context in
Expand All @@ -703,6 +703,7 @@ impl<S, T> SignalUpdate for Resource<S, T> {
})
.ok()
.flatten()
.flatten()
}
}

Expand Down Expand Up @@ -860,8 +861,9 @@ impl<S, T> SignalSet for Resource<S, T> {
)]
#[inline(always)]
fn try_set(&self, new_value: T) -> Option<T> {
self.update(|n| *n = Some(new_value));
None
let mut new_value = Some(new_value);
self.try_update(|n| *n = new_value.take());
new_value
}
}

Expand Down
32 changes: 25 additions & 7 deletions leptos_reactive/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1249,6 +1249,7 @@ impl Runtime {
.borrow_mut()
.insert(AnyResource::Serializable(state))
}

#[cfg_attr(
any(debug_assertions, feature = "ssr"),
instrument(level = "trace", skip_all,)
Expand All @@ -1259,13 +1260,35 @@ impl Runtime {
id: ResourceId,
f: impl FnOnce(&ResourceState<S, T>) -> U,
) -> U
where
S: 'static,
T: 'static,
{
self.try_resource(id, f).unwrap_or_else(|| {
panic!(
"couldn't locate {id:?} at {:?}",
std::panic::Location::caller()
);
})
}

#[cfg_attr(
any(debug_assertions, feature = "ssr"),
instrument(level = "trace", skip_all,)
)]
#[track_caller]
pub(crate) fn try_resource<S, T, U>(
&self,
id: ResourceId,
f: impl FnOnce(&ResourceState<S, T>) -> U,
) -> Option<U>
where
S: 'static,
T: 'static,
{
let resources = { self.resources.borrow().clone() };
let res = resources.get(id);
if let Some(res) = res {
res.map(|res| {
let res_state = match res {
AnyResource::Unserializable(res) => res.as_any(),
AnyResource::Serializable(res) => res.as_any(),
Expand All @@ -1281,12 +1304,7 @@ impl Runtime {
std::any::type_name::<T>(),
);
}
} else {
panic!(
"couldn't locate {id:?} at {:?}",
std::panic::Location::caller()
);
}
})
}

/// Returns IDs for all [`Resource`](crate::Resource)s found on any scope.
Expand Down

0 comments on commit 4a83ffc

Please sign in to comment.