Function use_async_with_options

Source
pub fn use_async_with_options<'hook, F, T, E>(
    future: F,
    options: UseAsyncOptions,
) -> impl 'hook + Hook<Output = UseAsyncHandle<T, E>>
where F: Future<Output = Result<T, E>> + 'static + 'hook, T: Clone + 'static + 'hook, E: Clone + 'static + 'hook,
Expand description

This hook returns state and a run callback for an async future with options. See use_async too.

§Example

use yew_hooks::prelude::*;

#[function_component(Async)]
fn async_test() -> Html {
    let state = use_async_with_options(async move {
        fetch("/api/user/123".to_string()).await
    }, UseAsyncOptions::enable_auto());
    
    html! {
        <div>
            {
                if state.loading {
                    html! { "Loading" }
                } else {
                    html! {}
                }
            }
            {
                if let Some(data) = &state.data {
                    html! { data }
                } else {
                    html! {}
                }
            }
            {
                if let Some(error) = &state.error {
                    html! { error }
                } else {
                    html! {}
                }
            }
        </div>
    }
}

async fn fetch(url: String) -> Result<String, String> {
    // You can use reqwest to fetch your http api
    Ok(String::from("Jet Li"))
}

§Note

When used in function components and hooks, this hook is equivalent to:

pub fn use_async_with_options<F, T, E>(
    future: F,
    options: UseAsyncOptions,
) -> UseAsyncHandle<T, E>
where
    F: Future<Output = Result<T, E>> + 'static,
    T: Clone + 'static,
    E: Clone + 'static,
{
    /* implementation omitted */
}
OSZAR »