pub fn use_future<'hook, F, T, O>(
init_f: F,
) -> impl 'hook + Hook<Output = SuspensionResult<UseFutureHandle<O>>>
Expand description
Use the result of an async computation, suspending while waiting.
Awaits the future returned from the first call to init_f
, and returns
its result in a UseFutureHandle
. Always suspends initially, even if
the future is immediately ready.
§Example
use gloo::net::http::Request;
const URL: &str = "https://en.wikipedia.org/w/api.php?\
action=query&origin=*&format=json&generator=search&\
gsrnamespace=0&gsrlimit=5&gsrsearch='New_England_Patriots'";
#[function_component]
fn WikipediaSearch() -> HtmlResult {
let res = use_future(|| async { Request::get(URL).send().await?.text().await })?;
let result_html = match *res {
Ok(ref res) => html! { res },
Err(ref failure) => failure.to_string().into(),
};
Ok(html! {
<p>
{"Wikipedia search result: "}
{result_html}
</p>
})
}
§Note
When used in function components and hooks, this hook is equivalent to:
/// Use the result of an async computation, suspending while waiting.
///
/// Awaits the future returned from the first call to `init_f`, and returns
/// its result in a [`UseFutureHandle`]. Always suspends initially, even if
/// the future is immediately [ready].
///
/// [ready]: std::task::Poll::Ready
///
/// # Example
///
/// ```
/// # use yew::prelude::*;
/// # use yew::suspense::use_future;
/// use gloo::net::http::Request;
///
/// const URL: &str = "https://en.wikipedia.org/w/api.php?\
/// action=query&origin=*&format=json&generator=search&\
/// gsrnamespace=0&gsrlimit=5&gsrsearch='New_England_Patriots'";
///
/// #[function_component]
/// fn WikipediaSearch() -> HtmlResult {
/// let res = use_future(|| async { Request::get(URL).send().await?.text().await })?;
/// let result_html = match *res {
/// Ok(ref res) => html! { res },
/// Err(ref failure) => failure.to_string().into(),
/// };
/// Ok(html! {
/// <p>
/// {"Wikipedia search result: "}
/// {result_html}
/// </p>
/// })
/// }
/// ```
pub fn use_future<F, T, O>(init_f: F) -> SuspensionResult<UseFutureHandle<O>>
where
F: FnOnce() -> T,
T: Future<Output = O> + 'static,
O: 'static,
{
/* implementation omitted */
}