2

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 => {});
  }

...?

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Can u write a example full code of display this value in my component?
@ReactRouter2 You just need to replace data.available_funds in your setState function with the code @khartnett has provided in the answer.
0

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 => {});
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.