I want to remove an item from an array getting the target.id, this app is for a cart, so in other words i want to remove an item from the cart when i click on the bin icon.
<span style={{fontSize:'50px'}}>Basket</span>
<ul style={{listStyle: 'none'}}>
{this.state.clickedNum.map((i) => <li key =
{this.props.gameData.id[i]} value={i}>
{this.props.gameData.gameNames[i]} <br/>
<img src={require('../assets/coins.png')} style={{width:'20px'}}/>
<strong> {this.props.gameData.prices[i]} Gil </strong>
<img src={require('../assets/bin.png')} style={{width:'20px', justifyContent:' flex-end'}} id={this.props.gameData.id[i]} onClick={this.removeClick}/>
<br/>
<hr style={{borderColor:'black'}} />
</li>
</ul>
This is the onClick={this.removeClick} function:
removeClick = (e) => {
e = e.target.id;
let clickedNum = this.state.clickedNum;
let isDisabled = this.state.isDisabled;
console.log("this is i" + e);
clickedNum.splice(e, 1);
isDisabled.splice(e,1);
this.setState({
clickedNum: clickedNum,
isDisabled:isDisabled
})
this.forceUpdate();
}
remove click is binded like this in the constructor function:
this.removeClick = this.removeClick.bind(this);
The problem comes that if you click the bin when there is more than one item in the cart it does not delete the first element and it does not always delete the correct item, however, if there is only one item in the cart it will delete the correct one.
I also note that :
console.log("this is i" + e);
returns the correct value (the id of button in which it was clicked on)
gameDataentry and have a disabled flag. We can't really help you based only on what's in the question above, but you're breaking two big rules of React state management: 1. You're directly modifying state (by usingspliceon an array in state), and...setState. State updates are asynchronous and can be batched, and so you can't do that. Usethis.setState(prevState => { /*...*/ })and use the information fromprevStateinstead. More: reactjs.org/docs/…