From 84caa35cef9fb2f87cda791b086e86e7ff1d3865 Mon Sep 17 00:00:00 2001 From: Greg Johnston Date: Mon, 5 May 2025 21:20:34 -0400 Subject: [PATCH] feat: add `.map()` and `.and_then()` on `LocalResource` (#3941) --- leptos_server/src/local_resource.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/leptos_server/src/local_resource.rs b/leptos_server/src/local_resource.rs index 3abfae1ab..e518f3f27 100644 --- a/leptos_server/src/local_resource.rs +++ b/leptos_server/src/local_resource.rs @@ -300,6 +300,34 @@ impl LocalResource { pub fn refetch(&self) { self.refetch.try_update(|n| *n += 1); } + + /// Synchronously, reactively reads the current value of the resource and applies the function + /// `f` to its value if it is `Some(_)`. + #[track_caller] + pub fn map(&self, f: impl FnOnce(&T) -> U) -> Option + where + T: 'static, + { + self.data.try_with(|n| n.as_ref().map(f))? + } +} + +impl LocalResource> +where + T: 'static, + E: Clone + 'static, +{ + /// Applies the given function when a resource that returns `Result` + /// has resolved and loaded an `Ok(_)`, rather than requiring nested `.map()` + /// calls over the `Option>` returned by the resource. + /// + /// This is useful when used with features like server functions, in conjunction + /// with `` and ``, when these other components are + /// left to handle the `None` and `Err(_)` states. + #[track_caller] + pub fn and_then(&self, f: impl FnOnce(&T) -> U) -> Option> { + self.map(|data| data.as_ref().map(f).map_err(|e| e.clone())) + } } impl IntoFuture for LocalResource