suspense.rs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 majoirty of suspense functionality by composing "suspenseful"
  12. //! primitives in our own custom components.
  13. use dioxus::prelude::*;
  14. fn main() {
  15. dioxus::desktop::launch(app)
  16. }
  17. #[derive(serde::Deserialize)]
  18. struct DogApi {
  19. message: String,
  20. }
  21. fn app(cx: Scope) -> Element {
  22. cx.render(rsx! {
  23. div {
  24. h1 {"Dogs are very important"}
  25. p {
  26. "The dog or domestic dog (Canis familiaris[4][5] or Canis lupus familiaris[5])"
  27. "is a domesticated descendant of the wolf which is characterized by an upturning tail."
  28. "The dog derived from an ancient, extinct wolf,[6][7] and the modern grey wolf is the"
  29. "dog's nearest living relative.[8] The dog was the first species to be domesticated,[9][8]"
  30. "by hunter–gatherers over 15,000 years ago,[7] before the development of agriculture.[1]"
  31. }
  32. h3 { "Illustrious Dog Photo" }
  33. Doggo { }
  34. }
  35. })
  36. }
  37. /// This component will re-render when the future has finished
  38. /// Suspense is achieved my moving the future into only the component that
  39. /// actually renders the data.
  40. fn Doggo(cx: Scope) -> Element {
  41. let fut = use_future(&cx, || async move {
  42. reqwest::get("https://dog.ceo/api/breeds/image/random/")
  43. .await
  44. .unwrap()
  45. .json::<DogApi>()
  46. .await
  47. });
  48. cx.render(match fut.value() {
  49. Some(Ok(resp)) => rsx! {
  50. button {
  51. onclick: move |_| fut.restart(),
  52. "Click to fetch another dog"
  53. }
  54. div {
  55. img {
  56. max_width: "500px",
  57. max_height: "500px",
  58. src: "{resp.message}",
  59. }
  60. }
  61. },
  62. Some(Err(_)) => rsx! { div { "loading dogs failed" } },
  63. None => rsx! { div { "loading dogs..." } },
  64. })
  65. }