Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
Count total Sum from fetched API / ReactJS

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 class="table">
            {tableList}
            <td><b className="number"> {totalSum} Eur</b></td>
            </table>
        </div>
    );
};
export default TableCardList;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 class="table">
        {tableList}
        <td><b className="number"> {totalSum} Eur</b></td>
      </table>
    </div>
  );
};

export default TableCardList;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!