pub fn use_async<F, T, E>(future: F) -> UseAsyncHandle<F, T, E> where
F: Future<Output = Result<T, E>> + 'static,
T: 'static,
E: 'static, Expand description
This hook returns state and a run callback for an async future.
Example
#[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 |_| {
let state = state.clone();
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"))
}