Skip to content

Commit

Permalink
use_future takes a closure
Browse files Browse the repository at this point in the history
  • Loading branch information
hamza1311 committed Apr 14, 2022
1 parent 5fec29a commit 48eb65f
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
40 changes: 35 additions & 5 deletions packages/yew/src/suspense/hooks.rs
@@ -1,7 +1,9 @@
#[cfg_attr(documenting, doc(cfg(any(target_arch = "wasm32", feature = "tokio"))))]
#[cfg(any(target_arch = "wasm32", feature = "tokio"))]
mod feat_futures {
use std::fmt;
use std::future::Future;
use std::ops::Deref;

use yew::prelude::*;
use yew::suspense::{Suspension, SuspensionResult};
Expand All @@ -10,22 +12,50 @@ mod feat_futures {
///
/// A [Suspension] is created from the passed future and the result of the future
/// is the output of the suspension.
pub struct UseFutureHandle<O> {
inner: UseStateHandle<Option<O>>,
}

impl<O> Deref for UseFutureHandle<O> {
type Target = O;

fn deref(&self) -> &Self::Target {
&*self.inner.as_ref().unwrap()
}
}

impl<T: fmt::Debug> fmt::Debug for UseFutureHandle<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("UseFutureHandle")
.field("value", &format!("{:?}", self.inner))
.finish()
}
}

#[hook]
pub fn use_future<T, F>(f: F) -> SuspensionResult<T>
pub fn use_future<F, T, O>(f: F) -> SuspensionResult<UseFutureHandle<O>>
where
T: Clone + 'static,
F: Future<Output = T> + 'static,
F: FnOnce() -> T + 'static,
T: Future<Output = O> + 'static,
O: '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)) }))
use_memo(
move |_| {
Suspension::from_future(async move {
output.set(Some(f().await));
})
},
(),
)
};

if suspension.resumed() {
Ok((*output).clone().unwrap())
Ok(UseFutureHandle { inner: output })
} else {
Err((*suspension).clone())
}
Expand Down
2 changes: 1 addition & 1 deletion packages/yew/tests/suspense.rs
Expand Up @@ -598,7 +598,7 @@ async fn effects_not_run_when_suspended() {
async fn use_suspending_future_works() {
#[function_component(Content)]
fn content() -> HtmlResult {
let _sleep_handle = use_future(async move {
let _sleep_handle = use_future(|| async move {
TimeoutFuture::new(50).await;
})?;

Expand Down

0 comments on commit 48eb65f

Please sign in to comment.