suspense.rs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #![allow(non_snake_case)]
  2. //! Suspense in Dioxus
  3. //!
  4. //! Currently, `rsx!` does not accept futures as values. To achieve the functionality
  5. //! of suspense, we need to make a new component that performs its own suspense
  6. //! handling.
  7. //!
  8. //! In this example, we render the `Doggo` component which starts a future that
  9. //! will cause it to fetch a random dog image from the Dog API. Since the data
  10. //! is not ready immediately, we render some loading text.
  11. //!
  12. //! We can achieve the majority of suspense functionality by composing "suspenseful"
  13. //! primitives in our own custom components.
  14. use dioxus::desktop::{Config, LogicalSize, WindowBuilder};
  15. use dioxus::prelude::*;
  16. fn main() {
  17. LaunchBuilder::desktop()
  18. .with_cfg(
  19. Config::new().with_window(
  20. WindowBuilder::new()
  21. .with_title("Doggo Fetcher")
  22. .with_inner_size(LogicalSize::new(600.0, 800.0)),
  23. ),
  24. )
  25. .launch(app)
  26. }
  27. fn app() -> Element {
  28. rsx! {
  29. div {
  30. h1 { "Dogs are very important" }
  31. p {
  32. "The dog or domestic dog (Canis familiaris[4][5] or Canis lupus familiaris[5])"
  33. "is a domesticated descendant of the wolf which is characterized by an upturning tail."
  34. "The dog derived from an ancient, extinct wolf,[6][7] and the modern grey wolf is the"
  35. "dog's nearest living relative.[8] The dog was the first species to be domesticated,[9][8]"
  36. "by hunter–gatherers over 15,000 years ago,[7] before the development of agriculture.[1]"
  37. }
  38. h3 { "Illustrious Dog Photo" }
  39. Doggo {}
  40. }
  41. }
  42. }
  43. /// This component will re-render when the future has finished
  44. /// Suspense is achieved my moving the future into only the component that
  45. /// actually renders the data.
  46. fn Doggo() -> Element {
  47. let fut = use_future(|| 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.value().read().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. }