Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add use_future hook to make consuming futures as suspense easier #2609

Merged
merged 5 commits into from
Apr 14, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions packages/yew/src/suspense/hooks.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#[cfg_attr(documenting, doc(cfg(any(target_arch = "wasm32", feature = "tokio"))))]
#[cfg(any(target_arch = "wasm32", feature = "tokio"))]
mod feat_futures {
use std::future::Future;

use yew::prelude::*;
use yew::suspense::{Suspension, SuspensionResult};

/// This hook is used to await a future in a suspending context.
///
/// A [Suspension] is created from the passed future and the result of the future
/// is the output of the suspension.
#[hook]
pub fn use_suspending_future<T, F>(f: F) -> SuspensionResult<T>
where
T: Clone + 'static,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any way to avoid this Clone bound?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about Rc<T>?

F: Future<Output = T> + 'static,
{
let output = use_state(|| None);

let suspension = {
let output = output.clone();

use_state(move || Suspension::from_future(async move { output.set(Some(f.await)) }))
};

if suspension.resumed() {
Ok((*output).clone().unwrap())
} else {
Err((*suspension).clone())
}
}
}

#[cfg(any(target_arch = "wasm32", feature = "tokio"))]
pub use feat_futures::*;
2 changes: 2 additions & 0 deletions packages/yew/src/suspense/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
//! This module provides suspense support.

mod component;
mod hooks;
mod suspension;

#[cfg(any(feature = "csr", feature = "ssr"))]
pub(crate) use component::BaseSuspense;
pub use component::Suspense;
pub use hooks::*;
pub use suspension::{Suspension, SuspensionHandle, SuspensionResult};
43 changes: 42 additions & 1 deletion packages/yew/tests/suspense.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use gloo::timers::future::TimeoutFuture;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::spawn_local;
use web_sys::{HtmlElement, HtmlTextAreaElement};
use yew::suspense::{Suspension, SuspensionResult};
use yew::suspense::{use_suspending_future, Suspension, SuspensionResult};

#[wasm_bindgen_test]
async fn suspense_works() {
Expand Down Expand Up @@ -593,3 +593,44 @@ async fn effects_not_run_when_suspended() {
);
assert_eq!(*counter.borrow(), 4); // effects ran 4 times.
}

#[wasm_bindgen_test]
async fn use_suspending_future_works() {
#[function_component(Content)]
fn content() -> HtmlResult {
let _sleep_handle = use_suspending_future(async move {
TimeoutFuture::new(50).await;
WorldSEnder marked this conversation as resolved.
Show resolved Hide resolved
})?;

Ok(html! {
<div>
{"Content"}
</div>
})
}

#[function_component(App)]
fn app() -> Html {
let fallback = html! {<div>{"wait..."}</div>};

html! {
<div id="result">
<Suspense {fallback}>
<Content />
</Suspense>
</div>
}
}

yew::Renderer::<App>::with_root(gloo_utils::document().get_element_by_id("output").unwrap())
.render();

TimeoutFuture::new(10).await;
let result = obtain_result();
assert_eq!(result.as_str(), "<div>wait...</div>");

TimeoutFuture::new(50).await;

let result = obtain_result();
assert_eq!(result.as_str(), r#"<div>Content</div>"#);
}