suspense.rs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //! Example: Suspense
  2. //! -----------------
  3. //! This example shows how the "use_fetch" hook is built on top of Dioxus' "suspense" API. Suspense enables components
  4. //! to wait on futures to complete before rendering the result into VNodes. These VNodes are immediately available in a
  5. //! "suspended" fashion and will automatically propogate to the UI when the future completes.
  6. //!
  7. //! Note that if your component updates or receives new props while it is awating the result, the future will be dropped
  8. //! and all work will stop. In this example, we store the future in a hook so we can always resume it.
  9. use dioxus::prelude::*;
  10. fn main() {}
  11. #[derive(serde::Deserialize)]
  12. struct DogApi {
  13. message: String,
  14. }
  15. const ENDPOINT: &str = "https://dog.ceo/api/breeds/image/random";
  16. pub static App: FC<()> = |cx| {
  17. let doggo = use_fetch(&cx, ENDPOINT, |cx, res: surf::Result<DogApi>| match res {
  18. Ok(res) => rsx!(in cx, img { src: "{res.message}"}),
  19. Err(_) => rsx!(in cx, p { "Failed to load doggo :("}),
  20. });
  21. cx.render(rsx!(
  22. div {
  23. h1 {"Waiting for a doggo..."}
  24. {doggo}
  25. }
  26. ))
  27. };
  28. fn use_fetch<'a, T: serde::de::DeserializeOwned + 'static>(
  29. cx: &impl Scoped<'a>,
  30. url: &str,
  31. g: impl FnOnce(dioxus_core::virtual_dom::SuspendedContext, surf::Result<T>) -> VNode<'a> + 'a,
  32. ) -> VNode<'a> {
  33. use futures::Future;
  34. use futures::FutureExt;
  35. use std::pin::Pin;
  36. // essentially we're doing a "use_effect" but with no dependent props
  37. let doggo_promise: &'a mut Pin<Box<dyn Future<Output = surf::Result<T>> + Send + 'static>> = cx
  38. .use_hook(
  39. move || surf::get(url).recv_json::<T>().boxed(),
  40. // just pass the future through
  41. |p| p,
  42. |_| (),
  43. );
  44. cx.suspend(doggo_promise, g)
  45. }