Update examples, add css

This commit is contained in:
Jonathan Kelley committed 2024-02-14 12:33:07 -08:00
1 parent 25d103c1a5
commit bdbae8ccb0
57 files changed
+964 -595

No files matched your search

+31 -13
View File
@@ -1,3 +1,12 @@
//! This example demonstrates a simple app that fetches a list of dog breeds and displays a random dog.
//!
//! The app uses the `use_signal` and `use_resource` hooks to manage state and fetch data from the Dog API.
//! `use_resource` is basically an async version of use_memo - it will track dependencies between .await points
//! and then restart the future if any of the dependencies change.
//!
//! You should generally throttle requests to an API - either client side or server side. This example doesn't do that
//! since it's unlikely the user will rapidly cause new fetches, but it's something to keep in mind.
use dioxus::prelude::*;
use std::collections::HashMap;
@@ -6,8 +15,18 @@ fn main() {
}
fn app() -> Element {
// Breed is a signal that will be updated when the user clicks a breed in the list
// `deerhound` is just a default that we know will exist. We could also use a `None` instead
let mut breed = use_signal(|| "deerhound".to_string());
// Fetch the list of breeds from the Dog API
// Since there are no dependencies, this will never restart
let breed_list = use_resource(move || async move {
#[derive(Debug, Clone, PartialEq, serde::Deserialize)]
struct ListBreeds {
message: HashMap<String, Vec<String>>,
}
let list = reqwest::get("https://dog.ceo/api/breeds/list/all")
.await
.unwrap()
@@ -19,7 +38,7 @@ fn app() -> Element {
};
rsx! {
for cur_breed in breeds.message.keys().take(10).cloned() {
for cur_breed in breeds.message.keys().take(20).cloned() {
li { key: "{cur_breed}",
button { onclick: move |_| breed.set(cur_breed.clone()),
"{cur_breed}"
@@ -29,22 +48,31 @@ fn app() -> Element {
}
});
// We can use early returns in dioxus!
// Traditional signal-based libraries can't do this since the scope is by default non-reactive
let Some(breed_list) = breed_list() else {
return rsx! { "loading breeds..." };
};
rsx! {
style { {include_str!("./assets/dog_app.css")} }
h1 { "Select a dog breed!" }
div { height: "500px", display: "flex",
ul { flex: "50%", {breed_list} }
div { flex: "50%", BreedPic { breed } }
ul { width: "100px", {breed_list} }
div { flex: 1, BreedPic { breed } }
}
}
}
#[component]
fn BreedPic(breed: Signal<String>) -> Element {
// This resource will restart whenever the breed changes
let mut fut = use_resource(move || async move {
#[derive(serde::Deserialize, Debug)]
struct DogApi {
message: String,
}
reqwest::get(format!("https://dog.ceo/api/breed/{breed}/images/random"))
.await
.unwrap()
@@ -61,13 +89,3 @@ fn BreedPic(breed: Signal<String>) -> Element {
None => rsx! { "loading image..." },
}
}
#[derive(Debug, Clone, PartialEq, serde::Deserialize)]
struct ListBreeds {
message: HashMap<String, Vec<String>>,
}
#[derive(serde::Deserialize, Debug)]
struct DogApi {
message: String,
}