I want to calculate totalSum. Api gives 'amount' rows, but I need to add them together and cant yet find correct function. I am still learning with reactjs.
const url = "http://127.0.0.1:8000/api/expense";
const TableCardList = () => {
const [data, setData] = useState([]);
const getData = async () => {
const response = await fetch(url);
const data = await response.json();
setData(data);
console.timeLog(data);
};
useEffect (() => {
getData();
}, []);
let tableList = data.map((row) => {
return (
<TableCard
key={row.id}
id={row.id}
created_at={row.created_at}
title={row.title}
category={row.category}
amount={row.amount}
/>
);
});
return(
<div className="row">
<table >
{tableList}
<td><b className="number"> {totalSum} Eur</b></td>
</table>
</div>
);
};
export default TableCardList;
CodePudding user response:
Array.prototype.reduce can do the trick
const url = "http://127.0.0.1:8000/api/expense";
const TableCardList = () => {
const [data, setData] = useState([]);
const [totalSum, setTotalSum] = useState(0);
useEffect(() => {
const getData = async () => {
const response = await fetch(url);
const data = await response.json();
setData(data);
console.timeLog(data);
};
getData()
}, []);
useEffect(() => {
const total = data.reduce((acc, row) => acc row.amount, 0);
setTotalSum(total)
}, [data]);
let tableList = data.map((row) => (
<TableCard
key={row.id}
id={row.id}
created_at={row.created_at}
title={row.title}
category={row.category}
amount={row.amount}
/>
));
return (
<div className="row">
<table >
{tableList}
<td><b className="number"> {totalSum} Eur</b></td>
</table>
</div>
);
};
export default TableCardList;