dioxus/examples/dog_app.rs

84 lines
2.3 KiB
Rust
Raw Normal View History

2022-01-03 06:12:39 +00:00
use dioxus::prelude::*;
use std::collections::HashMap;
2022-01-03 06:12:39 +00:00
fn main() {
2022-11-16 19:48:47 +00:00
dioxus_desktop::launch(|cx| {
cx.render(rsx! {
2022-11-18 06:55:46 +00:00
h1 {"Loading...."}
2022-11-16 19:48:47 +00:00
app_root {}
})
});
2022-01-03 06:12:39 +00:00
}
#[derive(Debug, Clone, PartialEq, serde::Deserialize)]
struct ListBreeds {
message: HashMap<String, Vec<String>>,
}
2022-11-16 19:48:47 +00:00
async fn app_root(cx: Scope<'_>) -> Element {
2022-11-18 04:00:39 +00:00
let breed = use_state(cx, || "deerhound".to_string());
2022-11-18 06:55:46 +00:00
2022-11-18 04:00:39 +00:00
let breeds = use_future!(cx, || async move {
2022-01-03 06:12:39 +00:00
reqwest::get("https://dog.ceo/api/breeds/list/all")
.await
.unwrap()
.json::<ListBreeds>()
.await
});
2022-11-16 19:48:47 +00:00
match breeds.await {
Ok(breeds) => cx.render(rsx! {
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%",
2022-11-17 06:10:04 +00:00
for cur_breed in breeds.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
}
2022-11-18 06:55:46 +00:00
div { flex: "50%", breed_pic { breed: breed.to_string() } }
2022-01-03 06:12:39 +00:00
}
}
}),
2022-11-16 19:48:47 +00:00
Err(_e) => cx.render(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,
}
2022-01-03 06:12:39 +00:00
#[inline_props]
2022-11-18 04:00:39 +00:00
async fn breed_pic(cx: Scope, breed: String) -> Element {
let fut = use_future!(cx, |breed| async move {
2022-03-09 23:11:40 +00:00
reqwest::get(format!("https://dog.ceo/api/breed/{}/images/random", breed))
.await
.unwrap()
.json::<DogApi>()
.await
2022-01-03 06:12:39 +00:00
});
2022-11-18 04:00:39 +00:00
match fut.await {
2022-11-16 19:48:47 +00:00
Ok(resp) => cx.render(rsx! {
2022-01-03 06:12:39 +00:00
div {
2022-11-16 19:48:47 +00:00
button {
onclick: move |_| fut.restart(),
"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-16 19:48:47 +00:00
}),
2022-11-18 04:00:39 +00:00
Err(_) => cx.render(rsx! { div { "loading dogs failed" } }),
2022-11-16 19:48:47 +00:00
}
2022-01-03 06:12:39 +00:00
}