'How can I increase and decrease the quantity in reactjs?
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>
);
};
Solution 1:[1]
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.
Solution 2:[2]
You can use these tricks to solve this problem -
- When you add or remove quantity from your stocks you can also update the database also using a 'PUT' method and set a dependency on your use effect over product. So when the product data updated in the database its also updated in the UI because of the dependency.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Avirup Mondal |