Embarking on my journey in frontend development and Svelte, I decided to dive into some experimentation.
Here is a counter component with buttons to increment or decrement the number of items:
Counter.svelte
<script>
export let quantity = 0;
function increase() {
quantity += 1;
}
function decrease() {
if (quantity > 0) {
quantity -= 1;
}
}
</script>
<button on:click={decrease}>-</button>{quantity}<button on:click={increase}>+</button>
App.svelte
<script>
... import dependencies
let products=[{ //data fetched from API
id: 1,
name: "potato",
price: 5
}, {
id: 2,
name: "garlic",
price: 3
}, {
id: 3,
name: "rice",
price: 10
}];
function checkout() {
//TODO: Send JSON data through POST request
}
</script>
{#each products as product}
{product.name} <Counter></Counter>
{/each}
<button on:click={checkout}>Checkout</button>
I'm wondering how to construct the following JSON object when the selected quantity for an item is greater than 0 after clicking the button. (assuming garlic has a quantity of 0)
[{
id: 1,
name: "potato",
price: 5,
quantity: 30
},{
id: 3,
name: "rice",
price: 10,
quantity: 400
}];