1
0

dog_app.rs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. 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. // `deerhound` is just a default that we know will exist. We could also use a `None` instead
  17. let mut breed = use_signal(|| "deerhound".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. style { {include_str!("./assets/dog_app.css")} }
  50. h1 { "Select a dog breed!" }
  51. div { height: "500px", display: "flex",
  52. ul { width: "100px", {breed_list} }
  53. div { flex: 1, BreedPic { breed } }
  54. }
  55. }
  56. }
  57. #[component]
  58. fn BreedPic(breed: Signal<String>) -> Element {
  59. // This resource will restart whenever the breed changes
  60. let mut fut = use_resource(move || async move {
  61. #[derive(serde::Deserialize, Debug)]
  62. struct DogApi {
  63. message: String,
  64. }
  65. reqwest::get(format!("https://dog.ceo/api/breed/{breed}/images/random"))
  66. .await
  67. .unwrap()
  68. .json::<DogApi>()
  69. .await
  70. });
  71. match fut.read_unchecked().as_ref() {
  72. Some(Ok(resp)) => rsx! {
  73. button { onclick: move |_| fut.restart(), "Click to fetch another doggo" }
  74. img { max_width: "500px", max_height: "500px", src: "{resp.message}" }
  75. },
  76. Some(Err(_)) => rsx! { "loading image failed" },
  77. None => rsx! { "loading image..." },
  78. }
  79. }