diff --git a/src/pages/home.rs b/src/pages/home.rs index bf9f0e8..f793424 100644 --- a/src/pages/home.rs +++ b/src/pages/home.rs @@ -1,5 +1,6 @@ use yew::prelude::*; +#[derive(Clone)] struct Product { id: i32, name: String, @@ -8,19 +9,30 @@ struct Product { price: f64, } +struct CartProduct { + product: Product, + quantity: i32, +} + struct State { products: Vec, + cart_products: Vec, } pub struct Home { state: State, + link: ComponentLink +} + +pub enum Msg { + AddToCart(i32) } impl Component for Home { - type Message = (); + type Message = Msg; type Properties = (); - fn create(_: Self::Properties, _: ComponentLink) -> Self { + fn create(_: Self::Properties, link: ComponentLink) -> Self { let products: Vec = vec![ Product { id: 1, @@ -37,15 +49,43 @@ impl Component for Home { price: 7.99, }, ]; + let cart_products = vec![]; + Self { state: State { products, + cart_products, }, + link, } } - fn update(&mut self, _: Self::Message) -> ShouldRender { - true + fn update(&mut self, message: Self::Message) -> ShouldRender { + match message { + Msg::AddToCart(product_id) => { + let product = self + .state + .products + .iter() + .find(|p: &&Product| p.id == product_id) + .unwrap(); + let cart_product = self + .state + .cart_products + .iter_mut() + .find(|cp: &&mut CartProduct| cp.product.id == product_id); + + if let Some(cp) = cart_product { + cp.quantity += 1; + } else { + self.state.cart_products.push(CartProduct { + product: product.clone(), + quantity: 1, + }) + } + true + } + } } fn change(&mut self, _: Self::Properties) -> ShouldRender { @@ -58,15 +98,29 @@ impl Component for Home { .products .iter() .map(|product: &Product| { + let product_id = product.id; html! {
{&product.name}
{"$"}{&product.price}
+
} }) .collect(); - html! { {products} } + + let cart_value = self + .state + .cart_products + .iter() + .fold(0.0, |acc, cp| acc + (cp.quantity as f64 * cp.product.price)); + + html! { +
+ {format!("Cart Value: {:.2}", cart_value)} + {products} +
+ } } }