dioxus/examples/reference/suspense.rs

34 lines
1.1 KiB
Rust
Raw Normal View History

2021-06-25 21:15:33 -04:00
//! Example: Suspense
//! -----------------
2021-07-16 16:11:25 -04:00
//! This example demonstrates how the use_suspense hook can be used to load and render asynchronous data. Suspense enables
//! components to wait on futures to complete before rendering the result into VNodes. These VNodes are immediately
//! available in a suspended" fashion and will automatically propogate to the UI when the future completes.
2021-06-25 21:15:33 -04:00
//!
2021-07-16 16:11:25 -04:00
//! Currently, suspense futures are non-restartable. In the future, we'll provide more granular control of how to start,
//! stop, and reset these futures.
2021-06-25 21:15:33 -04:00
use dioxus::prelude::*;
#[derive(serde::Deserialize)]
struct DogApi {
message: String,
}
const ENDPOINT: &str = "https://dog.ceo/api/breeds/image/random";
2021-07-16 16:11:25 -04:00
pub static Example: FC<()> = |cx| {
2021-07-27 11:28:05 -04:00
let doggo = use_suspense(
cx,
2021-07-16 16:11:25 -04:00
|| surf::get(ENDPOINT).recv_json::<DogApi>(),
|cx, res| match res {
2021-06-26 01:30:20 -04:00
Ok(res) => rsx!(in cx, img { src: "{res.message}" }),
Err(_) => rsx!(in cx, div { "No doggos for you :(" }),
2021-07-16 16:11:25 -04:00
},
);
2021-06-25 21:15:33 -04:00
cx.render(rsx!(
div {
h1 {"Waiting for a doggo..."}
{doggo}
}
))
};