feat: add <Await/> component to improve ergonomics of loading async blocks (#1091)

This commit is contained in:
Greg Johnston 2023-05-24 14:05:36 -04:00 committed by GitHub
parent 7f14da3026
commit e3ea889d5f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 68 additions and 0 deletions

66
leptos/src/await_.rs Normal file
View file

@ -0,0 +1,66 @@
use crate::Suspense;
use leptos_dom::IntoView;
use leptos_macro::{component, view};
use leptos_reactive::{
create_blocking_resource, create_resource, store_value, Scope, Serializable,
};
#[component]
/// Allows you to inline the data loading for an `async` block or
/// server function directly into your view. This is the equivalent of combining a
/// [`create_resource`] that only loads once (i.e., with a source signal `|| ()`) with
/// a [`Suspense`] with no `fallback`.
/// ```
/// # use leptos_reactive::*;
/// # use leptos_macro::*;
/// # use leptos_dom::*; use leptos::*;
/// # if false {
/// # run_scope(create_runtime(), |cx| {
/// async fn fetch_monkeys(monkey: i32) -> i32 {
/// // do some expensive work
/// 3
/// }
///
/// view! { cx,
/// <Await
/// future=|cx| fetch_monkeys(3)
/// view=|cx, data| {
/// view! { cx, <p>{*data} " little monkeys, jumping on the bed."</p> }
/// }
/// />
/// }
/// # });
/// # }
/// ```
pub fn Await<T, Fut, FF, VF, V>(
cx: Scope,
/// A function that takes a [`Scope`] and returns the [`Future`](std::future::Future) that
/// will the component will `.await` before rendering.
future: FF,
/// If `true`, the component will use [`create_blocking_resource`], preventing
/// the HTML stream from returning anything before `future` has resolved.
#[prop(optional)]
blocking: bool,
/// A function that takes a [`Scope`] and a reference to the resolved data from the `future`
/// renders a view.
view: VF,
) -> impl IntoView
where
Fut: std::future::Future<Output = T> + 'static,
FF: Fn(Scope) -> Fut + 'static,
V: IntoView,
VF: Fn(Scope, &T) -> V + 'static,
T: Serializable + 'static,
{
let res = if blocking {
create_blocking_resource(cx, || (), move |_| future(cx))
} else {
create_resource(cx, || (), move |_| future(cx))
};
let view = store_value(cx, view);
view! { cx,
<Suspense fallback=|| ()>
{move || res.with(cx, |data| view.with_value(|view| view(cx, data)))}
</Suspense>
}
}

View file

@ -147,6 +147,8 @@
mod additional_attributes;
pub use additional_attributes::*;
mod await_;
pub use await_::*;
pub use leptos_config::{self, get_configuration, LeptosOptions};
#[cfg(not(all(
target_arch = "wasm32",