Previously, I posted this query but now I've made changes to utilize a REST service for retrieving the item list. Everything functions as expected when the data is hardcoded, however, I encounter undefined values when using data from the REST service.
Counter.svelte
<script>
export let amount = 0;
function increment() {
amount += 1;
}
function decrement() {
if (amount > 0) {
amount -= 1;
}
}
</script>
<button on:click={decrement}>-</button>{amount}<button on:click={increment}>+</button>
Updated app.svelte to incorporate rest service in component creation
App.svelte
<script>
... import stuff
let items;
onMount( async() => {getItems()});
function getItemsFromDB() {
const getItems = (async() => {
'MY_REST_API",
{method:'GET'}
});
const data = await response.json();
items=data;
}
/*
items contains this:
[{
id: 1,
name: 'potato',
price: 5
}, {
id: 2,
name: 'garlic',
price: 3
}, {
id: 3,
name: 'rice',
price: 10
}];
*/
function purchase() {
const itemsWithAmount = items.filter(i => i.amount !== 0)
console.log(itemsWithAmount)
}
</script>
<ul>
{#each items as item}
<li>
{item.name} <Counter bind:amount={item.amount}/> <-- **UNDEFINED in page**
</li>
{/each}
</ul>
<button on:click={purchase}>Purchase</button>
The counter value turns out to be undefined once the page loads
Expected JSON:
[{
id: 1,
name: potato,
price: 5,
amount: 30
},{
id: 3,
name: rice,
price: 10,
amount: 400
}];