suspense.rs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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 propagate 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: Component = |cx| {
  16. let doggo = use_suspense(
  17. cx,
  18. || surf::get(ENDPOINT).recv_json::<DogApi>(),
  19. |cx, res| match res {
  20. Ok(res) => rsx!(
  21. cx,
  22. img {
  23. src: "{res.message}"
  24. }
  25. ),
  26. Err(_) => rsx!(cx, div { "No doggos for you :(" }),
  27. },
  28. );
  29. cx.render(rsx!(
  30. div {
  31. h1 {"Waiting for a doggo..."}
  32. {doggo}
  33. }
  34. ))
  35. };