suspense.rs 1.1 KB

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