'Why when i try run this code in reactjs, its always output wrong total number
i still newbie in reactjs, and i try to build a some project. this project its to display any product price and stock, but here this problem.
i try to sum this number to get a total price in my product in reactjs, but the output always like this. how to fix that...
import React from "react";
import { nanoid } from "nanoid";
import calc from "./calc";
export default class TableData extends React.Component {
constructor(props) {
super(props);
}
render() {
let arr = []
const {
data,
} = this.props;
const {
location, proformaItem,
} = data;
proformaItem.forEach((item) => {
const parseStock = JSON.parse(item.product_stock);
parseStock.forEach((stock) => {
let total = 0
if (stock[1] !== undefined) {
total += Number(stock[1]);
}
if (stock[5] !== undefined) {
total += Number(stock[5])
}
arr.push(total);
})
})
console.log(arr);
return (
<>
{
proformaItem.map((item, index) => {
const parseStock = JSON.parse(item.product_stock);
const parseItem = JSON.parse(item.items);
return (
<tr key={nanoid(12)}>
<td key={nanoid(12)}>{parseStock.map((key) => key[1])}</td>
<td key={nanoid(12)}>{parseStock.map((key) => key[3])}</td>
<td key={nanoid(12)}>{parseStock.map((key) => key[5])}</td>
<td key={nanoid(12)}>{item.categoryDescription}</td>
<td key={nanoid(12)}>{item.productDescription}</td>
<td key={nanoid(12)}>{
parseStock.map((item) => {
if (item[1] !== undefined && item[5] !== undefined) {
console.log(calc(item[1], item[5]));
}
})
}
</td>
<td key={nanoid(12)}>1</td>
<td key={nanoid(12)}>{parseItem.map((key) => key['qty'])}</td>
</tr>
)
})
}
</>
)
}
}
here's my data in json
{
"proformaItem": [
{
"product_id": "1852",
"productDescription": "Charcoal Size M",
"categoryDescription": "7200 Premium Tee",
"product_stock": "[{\"1\": 272}, {\"3\": 5328}, {\"5\": 177}]",
"items": "[{\"qty\": 1, \"productId\": 1852, \"proformaInfoId\": 556745, \"proformaItemId\": 2679283}]"
},
{
"product_id": "1801",
"productDescription": "Black Size S",
"categoryDescription": "7200 Premium Tee",
"product_stock": "[{\"1\": 745}, {\"3\": 30744}, {\"5\": 273}]",
"items": "[{\"qty\": 1, \"productId\": 1801, \"proformaInfoId\": 556745, \"proformaItemId\": 2679284}]"
},
]
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
