dioxus/examples/dog_app.rs

83 lines
2.3 KiB
Rust
Raw Normal View History

2022-01-03 06:12:39 +00:00
use dioxus::prelude::*;
2022-11-19 21:43:19 +00:00
use std::collections::HashMap;
2022-01-03 06:12:39 +00:00
fn main() {
dioxus_desktop::launch(|cx| render!(AppRoot {}));
2022-01-03 06:12:39 +00:00
}
#[derive(Debug, Clone, PartialEq, serde::Deserialize)]
struct ListBreeds {
message: HashMap<String, Vec<String>>,
}
#[component]
2024-01-14 05:12:21 +00:00
fn AppRoot(_: ()) -> Element {
let breed = use_signal(|| "deerhound".to_string());
2022-11-18 06:55:46 +00:00
2024-01-14 05:12:21 +00:00
let breeds = use_future(|| async move {
2022-01-03 06:12:39 +00:00
reqwest::get("https://dog.ceo/api/breeds/list/all")
.await
.unwrap()
.json::<ListBreeds>()
.await
});
match breeds.value()? {
2024-01-14 05:12:21 +00:00
Ok(breed_list) => rsx! {
2022-11-16 19:48:47 +00:00
div { height: "500px",
2022-02-21 20:39:47 +00:00
h1 { "Select a dog breed!" }
2022-01-03 06:12:39 +00:00
div { display: "flex",
ul { flex: "50%",
2023-07-14 23:15:20 +00:00
for cur_breed in breed_list.message.keys().take(10) {
2022-11-18 06:55:46 +00:00
li { key: "{cur_breed}",
button {
onclick: move |_| breed.set(cur_breed.clone()),
"{cur_breed}"
2022-01-03 06:12:39 +00:00
}
}
2022-11-17 06:10:04 +00:00
}
2022-01-03 06:12:39 +00:00
}
div { flex: "50%", BreedPic { breed: breed.to_string() } }
2022-01-03 06:12:39 +00:00
}
}
2024-01-14 05:12:21 +00:00
},
Err(_e) => rsx! { div { "Error fetching breeds" } },
2022-01-03 06:12:39 +00:00
}
}
2022-02-21 20:39:47 +00:00
#[derive(serde::Deserialize, Debug)]
struct DogApi {
message: String,
}
#[component]
fn BreedPic(breed: String) -> Element {
2024-01-14 05:12:21 +00:00
let fut = use_future(|breed| async move {
2023-01-28 02:35:46 +00:00
reqwest::get(format!("https://dog.ceo/api/breed/{breed}/images/random"))
2022-03-09 23:11:40 +00:00
.await
.unwrap()
.json::<DogApi>()
.await
2022-01-03 06:12:39 +00:00
});
match fut.value()? {
2022-11-19 21:21:02 +00:00
Ok(resp) => render! {
2022-01-03 06:12:39 +00:00
div {
2022-11-16 19:48:47 +00:00
button {
2022-11-22 18:05:13 +00:00
onclick: move |_| {
println!("clicked");
fut.restart()
},
2022-11-16 19:48:47 +00:00
"Click to fetch another doggo"
}
2022-01-03 06:12:39 +00:00
img {
2022-11-16 19:48:47 +00:00
src: "{resp.message}",
2022-01-03 06:12:39 +00:00
max_width: "500px",
max_height: "500px",
}
}
2022-11-19 21:21:02 +00:00
},
Err(_) => render! { div { "loading dogs failed" } },
2022-11-16 19:48:47 +00:00
}
2022-01-03 06:12:39 +00:00
}