Skip to content

Commit

Permalink
Add cart button
Browse files Browse the repository at this point in the history
  • Loading branch information
iwanbazz committed Aug 27, 2020
1 parent 63868b5 commit d525b58
Showing 1 changed file with 59 additions and 5 deletions.
64 changes: 59 additions & 5 deletions src/pages/home.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use yew::prelude::*;

#[derive(Clone)]
struct Product {
id: i32,
name: String,
Expand All @@ -8,19 +9,30 @@ struct Product {
price: f64,
}

struct CartProduct {
product: Product,
quantity: i32,
}

struct State {
products: Vec<Product>,
cart_products: Vec<CartProduct>,
}

pub struct Home {
state: State,
link: ComponentLink<Self>
}

pub enum Msg {
AddToCart(i32)
}

impl Component for Home {
type Message = ();
type Message = Msg;
type Properties = ();

fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self {
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
let products: Vec<Product> = vec![
Product {
id: 1,
Expand All @@ -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 {
Expand All @@ -58,15 +98,29 @@ impl Component for Home {
.products
.iter()
.map(|product: &Product| {
let product_id = product.id;
html! {
<div>
<img src={&product.image}/>
<div>{&product.name}</div>
<div>{"$"}{&product.price}</div>
<button onclick=self.link.callback(move |_| Msg::AddToCart(product_id))>{"Add To Cart"}</button>
</div>
}
})
.collect();
html! { <span>{products}</span> }

let cart_value = self
.state
.cart_products
.iter()
.fold(0.0, |acc, cp| acc + (cp.quantity as f64 * cp.product.price));

html! {
<div>
<span>{format!("Cart Value: {:.2}", cart_value)}</span>
<span>{products}</span>
</div>
}
}
}

0 comments on commit d525b58

Please sign in to comment.