Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

111
Vistas
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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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)
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda