1

I have a handler which doesn't quite work as I wanted... I need to be able to change the 'quantity' value of many items. Right now, with my handler, if i try with multiple items, they will get updated with the last value entered. So there must be a way for me to enter multiple values and update items differently.. here is what I did so far:

this.state.purchase.selected.map(item => {
                                    return (
                                        <Grid item xs={4}>
                                            <OrderItemsCard
                                                item={item}
                                                onChange={this.handleSelectedItemChange}
                                            />
                                        </Grid>
                                    )
                                })
      
        this.handleSelectedItemChange = this.handleSelectedItemChange.bind(this) 
 
 handleSelectedItemChange(event) {
        let query = Object.assign({}, this.state.purchase);
        query.selected.map(item => {
            item.quantity = event.target.value
        })
        this.setState({purchase: query})
    }
some guy
  • 45
  • 1
  • 2
  • 8
  • Simular question has been answered here before. Check out: https://stackoverflow.com/questions/28624763/retrieving-value-from-select-with-multiple-option-in-react – J.Lindebro Sep 30 '18 at 18:15

1 Answers1

1

If I understand correctly, you want a way to share your onChange function with multiple components, devising a way to distinguish the caller.

You can simply pass your item through to the onChange and use its values to determine the caller and perform whatever actions you wish.

This can be done as follows,

this.state.purchase.selected.map(item => {
  return ( 
    <Grid item xs={4}>
      <OrderItemsCard 
        item={item}
        onChange={(event) => this.handleSelectedItemChange(item, event)}
      />
    </Grid>
  );
})

handleSelectedItemChange(item, event) {
    // ...
}
Trent
  • 4,208
  • 5
  • 24
  • 46
  • The answer I was looking for. btw, is there a way to prevent the values from changing in real time ? cuz i am also displaying the initial ones – some guy Sep 30 '18 at 18:30
  • I'm not sure what you mean by "changing in real time". – Trent Sep 30 '18 at 18:54
  • Perhaps you're looking for `throttling` or `debouncing`. Give this article a read-through and see if it helps: https://codeburst.io/throttling-and-debouncing-in-javascript-b01cad5c8edf – Trent Sep 30 '18 at 18:56