Next, we will create a CartButton.svelte component that allows users to add items to the cart. This component will import cartItems from our cart store and provide a function to add new items.
In the CartButton.svelte file, we define an addItem function that takes an item as a parameter and updates cartItems by appending the new item. Additionally, we use $inspect to track state changes automatically.
<script lang="ts">
import { cartItems, setDiscount, getDiscount } from '$lib/cartStore.svelte.ts';
function addItem(item: string): void {
cartItems.push(item);
setDiscount(cartItems.length * 5); // Apply a discount based on item count
}
$inspect(cartItems, "Cart Items State");
</script>
<p>Current Discount: {getDiscount()}</p>
<button onclick={() => addItem("Item " + (cartItems.length + 1))}>
Add Item ({cartItems.length})
</button>
When the button is clicked, a new item is added to the cart, and the button's label updates to reflect the current number of items. Additionally, a discount is applied dynamically based on the number of items in the cart. This demonstrates Svelte's reactivity in action, as the UI automatically updates in response to changes in cartItems.