<script>
import {pinvalidable} from "@macfja/svelte-invalidable"
import { writable, derived } from "svelte/store"
let quantity = 1
let price = pinvalidable(writable(10), () => {
// Simulate long calculation + network access
return new Promise(r => setTimeout(() => r(Math.round(quantity * 10 * 0.8)), 1000))
})
let discount = derived([price], ([finalPrice]) => {
return (10 * quantity) - finalPrice
})
const increase = () => {
quantity++
$price = quantity * 10
// Indicate that the price should be recalculated
price.invalidate()
}
</script>
<h2>Shopping cart</h2>
<ul>
<li>
<ul>
<li>Product #1553879</li>
<li>Unit Price: 10¤</li>
<li>Quantity {quantity} <button id="increase-qty" on:click={increase}>+</button></li>
</ul>
</li>
</ul>
<dl>
<dt>Subtotal</dt>
<dd id="subtotal">{10 * quantity}¤</dd>
<dt>Total</dt>
<dd id="total">{$price}¤ ({$discount}¤ of discount)</dd>
</dl>