'Save item variable with Button Click
I want to create a web app which displays a number of customers from an API, and when I click on a customer, additional information for that customer will be shown.
So far I've fetched my API data as an array, created a list, and a button for each item in the array. Now when I push a customer button I want to call my API again but with the id as a parameter to access specific information about that customer.
However, to do so I need to save the "id" variable from the button that I pushed and I don't understand how to implement that.
This is what my app looks like (in Svelte)
<script>
import { onMount } from 'svelte'
let customers = []
onMount(() => {
fetch('https://europe-west3-gcp-task-346814.cloudfunctions.net/customer-function-1/getCustomer')
.then(response => response.json())
.then(result => customers = result)
})
function handleClick() {
}
</script>
{#each customers as customer (customer.id)}
<h2>
<button on:click={() => handleClick()}>
{customer.name}
</button>
</h2>
<p>
id: {customer.id}
</p>
<hr>
{/each}
Note that I'm rather new to JS and HTML.
Solution 1:[1]
You can do something like the code below. Basically you need to pass the customer that you get from the iteration to the handleClick function.
<script>
import { onMount } from 'svelte'
let customers = []
onMount(() => {
fetch('https://europe-west3-gcp-task-346814.cloudfunctions.net/customer-function-1/getCustomer')
.then(response => response.json())
.then(result => customers = result)
})
function handleClick(customer) {
// here you have access to the customer id by doing customer.id
console.log(customer)
}
</script>
{#each customers as customer (customer.id)}
<h2>
<button on:click={() => handleClick(customer)}>
{customer.name}
</button>
</h2>
<p>
id: {customer.id}
</p>
<hr>
{/each}
The code changed:
<button on:click={() => handleClick(customer)}>
and
function handleClick(customer) {
console.log(customer)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
