dog_app.rs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. li { key: "{cur_breed}",
  36. button { onclick: move |_| breed.set(cur_breed.clone()),
  37. "{cur_breed}"
  38. }
  39. }
  40. }
  41. }
  42. });
  43. // We can use early returns in dioxus!
  44. // Traditional signal-based libraries can't do this since the scope is by default non-reactive
  45. let Some(breed_list) = breed_list() else {
  46. return rsx! { "loading breeds..." };
  47. };
  48. rsx! {
  49. h1 { "Select a dog breed!" }
  50. div { height: "500px", display: "flex",
  51. ul { width: "100px", {breed_list} }
  52. div { flex: 1, BreedPic { breed } }
  53. }
  54. }
  55. }
  56. #[component]
  57. fn BreedPic(breed: Signal<String>) -> Element {
  58. // This resource will restart whenever the breed changes
  59. let mut fut = use_resource(move || async move {
  60. #[derive(serde::Deserialize, Debug)]
  61. struct DogApi {
  62. message: String,
  63. }
  64. reqwest::get(format!("https://dog.ceo/api/breed/{breed}/images/random"))
  65. .await
  66. .unwrap()
  67. .json::<DogApi>()
  68. .await
  69. });
  70. match fut.read_unchecked().as_ref() {
  71. Some(Ok(resp)) => rsx! {
  72. button { onclick: move |_| fut.restart(), "Click to fetch another doggo" }
  73. img { max_width: "500px", max_height: "500px", src: "{resp.message}" }
  74. },
  75. Some(Err(_)) => rsx! { "loading image failed" },
  76. None => rsx! { "loading image..." },
  77. }
  78. }