Skip to content

Instantly share code, notes, and snippets.

@jamiebuilds
Last active April 12, 2018 18:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamiebuilds/6d5f50e8a80cb52a0513441ab84c9afa to your computer and use it in GitHub Desktop.
Save jamiebuilds/6d5f50e8a80cb52a0513441ab84c9afa to your computer and use it in GitHub Desktop.
// @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