I am trying to update a value in the UI. When I click to update
, I have a button that will decrease by one In the database and be displayed in the UI’s quantity
section. when I click on the button, it’s decreased by one, but it doesn’t decrease if click again.
UI images enter image description here
//getting the data in the useEffectm updating quantity in handleUpdate
const { bookId } = useParams();
const [book, setBook] = useState({});
const [reload, setReload] = useState(true);
console.log(reload);
useEffect(() => {
const url = `url/book/${bookId}`;
fetch(url)
.then(res => res.json())
.then(data => setBook(data))
}, [reload])
const quantity = parseInt(book.quantity) - 1;
console.log(quantity);
const handleUpdate = () => {
const url = `url/books/${bookId}`
fetch(url, {
method: "PUT",
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({ quantity })
})
.then(res => res.json())
.then(data => {
console.log(data)
setReload(!reload)
alert("user updated")
})
}
//API for updating the value.
// update quantity
app.put('/books/:id', async (req, res) => {
const id = req.params.id;
console.log(req.body)
const quantity = req.body.quantity
console.log(quantity)
const filter = { _id: ObjectId(id) };
const options = { upsert: true };
const updatedQuantity = {
$set: { ...quantity - 1}
}
const result = await bookCollections.updateOne(filter, updatedQuantity, options);
res.send(result);
});
//displaying the updated value
<li className="m-1">
<Link className="inline-flex text-center text-gray-100 py-1 px-3 rounded-full bg-blue-500 hover:bg-blue-600 transition duration-150 ease-in-out" to="#0">Quantity: {quantity}</Link>
</li>
//calling the function in button.
<button onClick={handleUpdate} className="btn btn-outline text-white">Delevered</button>
2
Answers
When decreasing the value by one, try storing it in a state. And use the current value from database as the default value of the state. for example,
const [newQuantity, setNewQuantity] = useState(product.quantity);
after fetching, set the new value like this:
fetch(url, {
method: ‘PUT’,
headers: {
‘content-type’: ‘application/json’
},
body: JSON.stringify(updatedQuantity)
You are almost done. In server side just destructure the quantity as it is already updated. it should look like,
and in onClick function pass id both during defining function and calling function inside button
It should work:)