I have a button and an input form. When clicking the button, my product quantity decreases by 1 and increases quantity when submitting the form. Quantity increases with the form value. How can I complete this problem in Reactjs?
import React, { useEffect, useState } from "react";
const InventoryDetails = () => {
const [inventory, setInventory] = useState({});
useEffect(() => {
const url = `inventory.json`;
fetch(url)
.then((res) => res.json())
.then((data) => setInventory(data));
}, []);
const handleDelivered = () => {
// can't understand what can I do here.
};
const restockItem = () => {};
return (
<div>
<div>
<h6> Quantity: {inventory.quantity} </h6>
<button onClick={handleDelivered}>Delivered</button>
</div>
<div>
<h3>Restock the items</h3>
<form onSubmit={restockItem}>
<input
type="number"
name="number"
id=""
placeholder="Enter quantity"
required
/>
<input className="" type="submit" value="Restock" />
</form>
</div>
</div>
);
};
Here I wrote two functions handleDelivered and restockItem. Put restockItem function to your button and try them:
handleDelivered = () => {
setInventory({
...inventory,
quantity: inventory.quantity - 1,
});
};
restockItem = (event) => {
event.preventDefault();
setInventory({
...inventory,
quantity: inventory.quantity + parseInt(event.target[0].value),
});
};
You have to set the state of the inventory when you're going to make changes, ...inventory is destructing the inventory object to get all the fields inside and change only quantity field, preventDefault is just my habit to prevent submitting, don't forget to type check the quantity field.
You can use these tricks to solve this problem -