Search code examples
sappersvelte-3

svelte-sapper each block list item selection for deletion - get the id


I have a list of orders stored in a db. I use each block to display all orders with a delete button. When I click the delete button, I need to get the id of the CLICKED list item so I can look that order in the db and delete it. I don't know how to get the id of the CLICKED list item and pass it to handledelete function. How do I do that in svelte/sapper?

My code for the page that display all orders :

<script>
 
  let orderz =[]

  function handlesave() {
     //save all the order data to db...    
  } // handlesave


  function handleDelete () {
  

  fetch('order', {
  method: 'POST',
  credentials : 'include',
  headers: {
  'Accept': 'application/json',
  'Content-type' : 'application/json'
  },
  body: JSON.stringify({
  // order id to send it to server to delete it from the db
   
  })
  }).then(response => response.json())
  .then(responseJson => {
  console.log("xxxxxxx:", responseJson.orderdetails )      
  })
  .catch(error => console.log(error));

}

</script>


<form on:submit|preventDefault={handlesave}>
  <button type="submit">Place Order</button>
</form>

<ul>
  {#each orderz as order}
  <li >
    <p >{order.vendorid} - {order.vendorname} - {order.item} 
         - {order.price}</p>
    <button on:click|once={handleDelete}>Delete</button>
  </li>
  
  {/each}
</ul>

Solution

  • You can tell the delete function which id was clicked by simply passing it in as an argument to the function:

    function handleDelete(id) {
      // Delete logic here
    }
    
    <button on:click="{() => handleDelete(id)}">Delete</button>
    

    !! Note that you should not call handleDelete directly in your markup as this will execute the function immediately upon rendering (and thus effectively delete your entry as soon as it appears on screen)