pub fn use_async<'hook, F, T, E>(
future: F,
) -> impl 'hook + Hook<Output = UseAsyncHandle<T, E>>Expand description
This hook returns state and a run callback for an async future.
§Example
use yew_hooks::prelude::*;
#[function_component(Async)]
fn async_test() -> Html {
let state = use_async(async move {
fetch("/api/user/123".to_string()).await
});
let onclick = {
let state = state.clone();
Callback::from(move |_| {
state.run();
})
};
html! {
<div>
<button {onclick} disabled={state.loading}>{ "Start loading" }</button>
{
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:
/// This hook returns state and a `run` callback for an async future.
///
/// # Example
///
/// ```rust
/// # use yew::prelude::*;
/// #
/// use yew_hooks::prelude::*;
///
/// #[function_component(Async)]
/// fn async_test() -> Html {
/// let state = use_async(async move {
/// fetch("/api/user/123".to_string()).await
/// });
///
/// let onclick = {
/// let state = state.clone();
/// Callback::from(move |_| {
/// state.run();
/// })
/// };
///
/// html! {
/// <div>
/// <button {onclick} disabled={state.loading}>{ "Start loading" }</button>
/// {
/// 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"))
/// }
/// ```
pub fn use_async<F, T, E>(future: F) -> UseAsyncHandle<T, E>
where
F: Future<Output = Result<T, E>> + 'static,
T: Clone + 'static,
E: Clone + 'static,
{
/* implementation omitted */
}