1
0

use_future.rs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #![allow(non_snake_case, unused)]
  2. use dioxus::prelude::*;
  3. fn main() {
  4. dioxus_desktop::launch(App);
  5. }
  6. #[derive(serde::Deserialize, Debug)]
  7. struct ApiResponse {
  8. #[serde(rename = "message")]
  9. image_url: String,
  10. }
  11. #[rustfmt::skip]
  12. fn App(cx: Scope) -> Element {
  13. // ANCHOR: use_future
  14. let future = use_future(cx, (), |_| async move {
  15. reqwest::get("https://dog.ceo/api/breeds/image/random")
  16. .await
  17. .unwrap()
  18. .json::<ApiResponse>()
  19. .await
  20. });
  21. // ANCHOR_END: use_future
  22. // ANCHOR: render
  23. cx.render(match future.value() {
  24. Some(Ok(response)) => rsx! {
  25. button {
  26. onclick: move |_| future.restart(),
  27. "Click to fetch another doggo"
  28. }
  29. div {
  30. img {
  31. max_width: "500px",
  32. max_height: "500px",
  33. src: "{response.image_url}",
  34. }
  35. }
  36. },
  37. Some(Err(_)) => rsx! { div { "Loading dogs failed" } },
  38. None => rsx! { div { "Loading dogs..." } },
  39. })
  40. // ANCHOR_END: render
  41. }
  42. #[rustfmt::skip]
  43. #[inline_props]
  44. fn RandomDog(cx: Scope, breed: String) -> Element {
  45. // ANCHOR: dependency
  46. let future = use_future(cx, (breed,), |(breed,)| async move {
  47. reqwest::get(format!("https://dog.ceo/api/breed/{breed}/images/random"))
  48. .await
  49. .unwrap()
  50. .json::<ApiResponse>()
  51. .await
  52. });
  53. // ANCHOR_END: dependency
  54. cx.render(rsx!(()))
  55. }