This is unreleased documentation for Yew Next version.
For up-to-date documentation, see the latest version on docs.rs.
yew::suspense

Function use_future

source
pub fn use_future<'hook, F, T, O>(
    init_f: F,
) -> impl 'hook + Hook<Output = SuspensionResult<UseFutureHandle<O>>>
where F: FnOnce() -> T + 'hook, T: Future<Output = O> + 'static + 'hook, O: 'static + 'hook,
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:

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 */
}