Check out the: GITHUB REPOSITORY
The quantity is set to 1 but the total (bottles) isn’t updated
In onMouseLeave there is a function that each time set the quantity to 1 when triggered.
The problem is the value showed in bottles isn’t updated once the value of the quantity has changed.
Quantity is a state element.
The problem is not that I wrote something wrong in the code, I’ve actually re-written the code so it might have some errors in it but that’s not the point.
Here’s a simplified version of my code:
class Example extends Component {
state = {
quantity: 1,
key: 0,
hovering: false
}
//EACH TIME THE QUANTITY IS CHANGED THIS FUNCTION TRIGGERS
handleChange(event) {
this.setState({ quantity: event.target.value, key: event.target.id })
}
//THE OBJECT PASSED
products: [
{id:1,price:10},
{id:2,price:20},
{id:3,price:30}
]
render() {
const { products } = this.props;
const productsList = products.map(product => {
return (
<div key={product.id}>
<div onMouseLeave={() => this.setState({ hovering: false, quantity: 1 })}>
Select a quantity:
<input type="number" defaultValue={1} min={1} onChange={this.handleChange.bind(this)} id={product.id} />
Total: $ {{(this.state.key + "") === (product.id + "") ? (product.price * this.state.quantity).toFixed(2) : product.price}}
<div onMouseEnter={() => this.setState({ hovering: true })}>BUY </div>
</div>
<div/>
I think I am probably using the wrong approach.
Maybe if I added the quantity to the object based on the value of this.state.quantity of a certain element so I don’t have to reset the quantity to 1 would be better but I don’t know how to add the {quantity:this.state.quantity}
to the products object.
Then I would proceed adding this to show the value:
Total: {this.state.key + "" === product.id + "" && product.quantity }
What I will need to do after:
Once the user has clicked on Buy I do actually need that quantity to be added to an array of objects.
I was thinking about something like that:
var newArr = this.state.arr;
var newArray = this.state.arr.slice();
newArray.push({id:this.state.key, quantity: ths.state.quantity});
this.setState({arr:newArray})
and once they are done there is a button to send the array of the objects to the next process.
adding an onClick handler to the buy button and passing the id and the quantity (also the total but it is not strictly necessary).