i am trying decrease quantity value when button is clicked and sent it to database.i got product
object as props. i destructure quantity value and set quantity value as usestate initialize value
const { description, img, name, supplier, quantity, price } = product
const [updateQuantity, setUpdateQuantity] = useState(quantity)
useEffect(() => {
setUpdateQuantity(quantity)
}, [quantity])
then i created a function handleDecrease
function and linked it with button.heres my function
const handleDecrease = () => {
console.log(updateQuantity);
setUpdateQuantity(updateQuantity - 1)
fetch(`http://localhost:4000/product/${id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ updateQuantity: updateQuantity }),
})
.then((res) => res.json())
.then((data) => console.log(data));
}
its working fine.when i click button quantity value is decreasing and mongo database is updating.but when i fresh this page i got updateQuantity
value undefined and quantity
object value null
my index.js code of express app
app.put('/product/:id', async (req, res) => {
const id = req.params.id
const data = req.body
console.log(data);
console.log(id);
const filter = { _id: ObjectId(id) }
const options = { upsert: true };
const updateDoc = {
$set: {
updateQuantity: data.updateQuantity,
},
};
const result = await productCollection.updateOne(filter, updateDoc, options);
res.send(result)
})
.what did i do wrong? why i am getting null
Try to change your updateDoc
condition:
app.put('/product/:id', async (req, res) => {
const id = req.params.id;
const data = req.body;
const filter = { _id: ObjectId(id) };
const options = { upsert: true };
const updateDoc = { updateQuantity: data.updateQuantity };
const result = await productCollection.updateOne(filter, updateDoc, options);
res.send(result);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.