suspense.rs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //! Suspense in Dioxus
  2. //!
  3. //! Currently, `rsx!` does not accept futures as values. To achieve the functionality
  4. //! of suspense, we need to make a new component that performs its own suspense
  5. //! handling.
  6. //!
  7. //! In this example, we render the `Doggo` component which starts a future that
  8. //! will cause it to fetch a random dog image from the Dog API. Since the data
  9. //! is not ready immediately, we render some loading text.
  10. //!
  11. //! We can achieve the majority of suspense functionality by composing "suspenseful"
  12. //! primitives in our own custom components.
  13. use dioxus::desktop::{Config, LogicalSize, WindowBuilder};
  14. use dioxus::prelude::*;
  15. fn main() {
  16. LaunchBuilder::new()
  17. .with_cfg(desktop! {
  18. Config::new().with_window(
  19. WindowBuilder::new()
  20. .with_title("Doggo Fetcher")
  21. .with_inner_size(LogicalSize::new(600.0, 800.0)),
  22. )
  23. })
  24. .launch(app)
  25. }
  26. fn app() -> Element {
  27. rsx! {
  28. div {
  29. h1 { "Dogs are very important" }
  30. p {
  31. "The dog or domestic dog (Canis familiaris[4][5] or Canis lupus familiaris[5])"
  32. "is a domesticated descendant of the wolf which is characterized by an upturning tail."
  33. "The dog derived from an ancient, extinct wolf,[6][7] and the modern grey wolf is the"
  34. "dog's nearest living relative.[8] The dog was the first species to be domesticated,[9][8]"
  35. "by hunter–gatherers over 15,000 years ago,[7] before the development of agriculture.[1]"
  36. }
  37. h3 { "Illustrious Dog Photo" }
  38. Doggo {}
  39. }
  40. }
  41. }
  42. /// This component will re-render when the future has finished
  43. /// Suspense is achieved my moving the future into only the component that
  44. /// actually renders the data.
  45. #[component]
  46. fn Doggo() -> Element {
  47. let mut fut = use_resource(move || async move {
  48. #[derive(serde::Deserialize)]
  49. struct DogApi {
  50. message: String,
  51. }
  52. reqwest::get("https://dog.ceo/api/breeds/image/random/")
  53. .await
  54. .unwrap()
  55. .json::<DogApi>()
  56. .await
  57. });
  58. match fut.read_unchecked().as_ref() {
  59. Some(Ok(resp)) => rsx! {
  60. button { onclick: move |_| fut.restart(), "Click to fetch another doggo" }
  61. div { img { max_width: "500px", max_height: "500px", src: "{resp.message}" } }
  62. },
  63. Some(Err(_)) => rsx! { div { "loading dogs failed" } },
  64. None => rsx! { div { "loading dogs..." } },
  65. }
  66. }