dog_app.rs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. //! This example demonstrates a simple app that fetches a list of dog breeds and displays a random dog.
  2. //!
  3. //! The app uses the `use_signal` and `use_resource` hooks to manage state and fetch data from the Dog API.
  4. //! `use_resource` is basically an async version of use_memo - it will track dependencies between .await points
  5. //! and then restart the future if any of the dependencies change.
  6. //!
  7. //! You should generally throttle requests to an API - either client side or server side. This example doesn't do that
  8. //! since it's unlikely the user will rapidly cause new fetches, but it's something to keep in mind.
  9. use dioxus::prelude::*;
  10. use std::collections::HashMap;
  11. fn main() {
  12. dioxus::launch(app);
  13. }
  14. fn app() -> Element {
  15. // Breed is a signal that will be updated when the user clicks a breed in the list
  16. // `shiba` is just a default that we know will exist. We could also use a `None` instead
  17. let mut breed = use_signal(|| "shiba".to_string());
  18. // Fetch the list of breeds from the Dog API
  19. // Since there are no dependencies, this will never restart
  20. let breed_list = use_resource(move || async move {
  21. #[derive(Debug, Clone, PartialEq, serde::Deserialize)]
  22. struct ListBreeds {
  23. message: HashMap<String, Vec<String>>,
  24. }
  25. let list = reqwest::get("https://dog.ceo/api/breeds/list/all")
  26. .await
  27. .unwrap()
  28. .json::<ListBreeds>()
  29. .await;
  30. let Ok(breeds) = list else {
  31. return rsx! { "error fetching breeds" };
  32. };
  33. rsx! {
  34. for cur_breed in breeds.message.keys().take(20).cloned() {
  35. button { onclick: move |_| breed.set(cur_breed.clone()),
  36. "{cur_breed}"
  37. }
  38. }
  39. }
  40. });
  41. // We can use early returns in dioxus!
  42. // Traditional signal-based libraries can't do this since the scope is by default non-reactive
  43. let Some(breed_list) = breed_list() else {
  44. return rsx! { "loading breeds..." };
  45. };
  46. rsx! {
  47. h1 { "Select a dog breed: {breed}" }
  48. BreedPic { breed }
  49. div { width: "400px", {breed_list} }
  50. }
  51. }
  52. #[component]
  53. fn BreedPic(breed: Signal<String>) -> Element {
  54. // This resource will restart whenever the breed changes
  55. let mut fut = use_resource(move || async move {
  56. #[derive(serde::Deserialize, Debug)]
  57. struct DogApi {
  58. message: String,
  59. }
  60. reqwest::get(format!("https://dog.ceo/api/breed/{breed}/images/random"))
  61. .await
  62. .unwrap()
  63. .json::<DogApi>()
  64. .await
  65. });
  66. match fut.read_unchecked().as_ref() {
  67. Some(Ok(resp)) => rsx! {
  68. div {
  69. button { onclick: move |_| fut.restart(), padding: "5px", background_color: "gray", color: "white", border_radius: "5px", "Click to fetch another doggo" }
  70. img { max_width: "500px", max_height: "500px", src: "{resp.message}" }
  71. }
  72. },
  73. Some(Err(_)) => rsx! { "loading image failed" },
  74. None => rsx! { "loading image..." },
  75. }
  76. }