user10713925
user10713925

Reputation:

Display a sum of value in json in React.js

I have this json and I would like to view a sum of available_funds in my Component in React.js. If is this possible? could I ask for an example of viewing this? Because I can not do it.

[
  {
    id: 1,
    id_owner: 1,
    account_bill: 123456789,
    available_funds: 100
  },
  {
    id: 2,
    id_owner: 1,
    account_bill: 111111111,
    available_funds: 20
  }
]

React.js component:

class AvailableFunds extends Component {
  constructor() {
    super();
    this.state = {
      availableFunds: '',
      isLoading: true,
    };
  }

  componentDidMount() {
    axios
      .get('http://localhost:3000/api/bills/1')
      .then(({ data }) => {
        console.log(data);
        this.setState({
          availableFunds: data.available_funds,
          isLoading: false
        });
      })
      .catch(err => {});
  }

...?

Upvotes: 2

Views: 3048

Answers (2)

Kubwimana Adrien
Kubwimana Adrien

Reputation: 2531

Try this:

componentDidMount() {
    axios
        .get('http://localhost:3000/api/bills/1')
        .then(({ data }) => {
        var sum = 0;
        if(typeof data == 'object'){
            data.forEach(funds => {
                sum += parseFloat(funds.available_funds);
            });
        }
        this.setState({
            availableFunds: sum,
            isLoading: false
        });
    })
    .catch(err => {});
}

Upvotes: 0

khartnett
khartnett

Reputation: 861

if your data is an array of objects, you can use reduce to get the sum:

data.reduce((accumulator, currentValue) => accumulator + currentValue.available_funds, 0)

Upvotes: 3

Related Questions