While delving into Node.js, I encountered an issue with my cartData.json file not updating properly. Here's the code snippet in question:
routes.post("/cart", (req, res, next) => {
let prodId = req.body.productId;
let productList = [];
let cartList = [];
fs.readFile(productListDatapath_dir, (err, data) => {
if (!err) productList = JSON.parse(data);
});
fs.readFile(cartListDatapath_dir, (err, data) => {
if (!err) {
cartList = JSON.parse(data);
cartList.forEach((product) => {
prodId = prodId.replace(/\s+/g, " ").trim();
if (product.Id === prodId) {
console.log("If block executed");
product.quantity += 1;
}
else
{
console.log("else block executed");
productList.forEach((element) => {
prodId = prodId.replace(/\s+/g, " ").trim();
if (element.Id === prodId) {
element.quantity = 1;
cartList.push(element);
}
});
}
});
}
fs.writeFile(cartListDatapath_dir, JSON.stringify(cartList), (err) => {
console.log(err);
});
});
res.redirect("/cart");
});
module.exports = routes;
Here is the JSON data in the cart list:
[
{
"title": "camera",
"imageUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/I...",
"description": "girl clicking picture",
"amount": "1254",
"Id": "12345",
"quantity": 1
},
{
"title": "Mountain Picture",
...
]
When attempting to add the same object to the cart, the "else" block executes instead of the "if" block. Refer to the UI image below:
https://i.sstatic.net/88ors.png
Upon clicking multiple times on the image, the data in CartData.json appears as follows:
[
{
"title": "camera",
"imageUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/I...",
...
]
Related UI image can be found here:
https://i.sstatic.net/CaOSG.png
Additionally, a screenshot of the terminal is provided:
https://i.sstatic.net/jlUmZ.png
If anyone could shed light on why this issue is occurring and offer solutions, it would be greatly appreciated!