0

I am a newbie and trying to delete an item from array by clicking a button. However, I could not retrieve the id I want. All I could get from e.target was the "input" itself, not the whole item, let alone the id.

//some other stuff

  deleteDrink = (event) => {
    console.log(event.target)
  }

return(
//blahblahblah[enter image description here][1]
orders.map((order, i) => (
            <Order
              key={orders[i].id}
              drink={orders[i].drink}
              price={orders[i].price}
              quantities={orders[i].number}
              note={orders[i].note}
              deleteDrink={this.deleteDrink}
            />
    ) ```

When I clicked the button, all I can get is:
<input class="delete-button br4 w-10 grow" type="button" value="Delete"></input>

what should I do to retrieve the id?


  [1]: https://i.stack.imgur.com/KM7Ng.jpg
Lin Chen
  • 13
  • 4

1 Answers1

0

Instead of setting the handler to this.deleteDrink, set a handler which calls deleteDrink with the ID (or index) of the element to be deleted:

deleteDrink={() => { this.deleteDrink(order.id); }}
deleteDrink = (id) => {
  console.log('deleting', id)
}

To delete the particular order when deleteDrink is called, perhaps you'd want something like this:

deleteDrink={() => { this.deleteDrink(i); }}
// Example if you're using hooks:
deleteDrink = (i) => {
  setOrders([
    ...orders.slice(0, i),
    ...orders.slice(i + 1)
  ]);
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thank you so much, that is exactly what I needed!! – Lin Chen Aug 23 '20 at 03:00
  • After awhile, when I looked back, I still don't know why this could work. "set a handler which calls deleteDrink with the ID" why&how can I get the ID by calling the deleteDrink? what's the mechanism behind this logic? – Lin Chen Sep 15 '20 at 03:33
  • The ID is saved in the *closure* created when the ` console.log(k); }` will log the current index of the element, because the `i` variable for each element is saved in the closure for the event listener. – CertainPerformance Sep 15 '20 at 04:03
  • I still find this concept quite vague. Is there any website or tutorial about this part? My main problem is that why can't I call deleteDrink={this.deleteDrink} but call deleteDrink={() => { this.deleteDrink(order.id); }} . I'm really thankful for your response and patience. – Lin Chen Sep 16 '20 at 02:25
  • If you do `deleteDrink={this.deleteDrink}`, you aren't passing the ID, so there isn't a (good) way to know which item to delete from the array. Closures are a big topic, you can read about them here: https://stackoverflow.com/questions/111102/how-do-javascript-closures-work and https://www.google.com/search?q=closure+js – CertainPerformance Sep 16 '20 at 02:27
  • Thank you so much for answering my stupid question. Wish you a wonderful day!! – Lin Chen Sep 16 '20 at 07:07