Last active
April 12, 2018 18:02
-
-
Save jamiebuilds/6d5f50e8a80cb52a0513441ab84c9afa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @flow | |
import React from 'react'; | |
import { Container, Subscribe } from 'unstated'; | |
function formatPrice(price: number) { | |
return `$${Math.round(price * 100) / 100} USD`; | |
} | |
class CartItem { | |
constructor(name: string, price: number) { | |
this.name = name; | |
this.price = price; | |
} | |
get description() { | |
return `${name}: ${formatPrice(this.price)}`; | |
} | |
} | |
type State = { | |
items: Array<CartItem> | |
}; | |
class CartContainer extends Container<State> { | |
state = { | |
items: [], | |
}; | |
addItem(name: string, price: number) { | |
this.setState({ | |
items: this.state.items.concat(new CartItem(name, price)), | |
}); | |
} | |
get total() { | |
return this.state.items.reduce((total, item) => total + item.price, 0); | |
} | |
} | |
export default function Cart(props: {}) { | |
return ( | |
<Subscribe to={[CartContainer]}> | |
{cart => ( | |
<div> | |
<h1>Cart</h1> | |
<ul> | |
{cart.state.items.map(item => ( | |
<li key={item.name}>{item.description}</li> | |
))} | |
</ul> | |
<div> | |
Total: ${formatPrice(cart.total)} | |
</div> | |
</div> | |
)} | |
</Subscribe> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment