suspense.rs 1.1 KB

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