Attempting to sum values in database array returning 'NaN' error in React front end

Hey,

I’m attempting to take figures from an array of objects in my React frontend, MongoDB Database, and sum them together.

To do this, I have built a ‘reduce’ function, which I’m using on my state.

const sumBalance = this.state.debts.reduce(function(previousValue, currentValue) {
          return (
            previousValue.balance + currentValue.balance
          )
        }, 0)

However, every time I try to access my app now I get a ‘NaN’ where the ‘sumBalance’ function is rendering.

In case it’s not clear, I am attempting to take the ‘balance’ value from each of my database objects, and sum them together. I then want to render that in this component:

<IndividualDebtSummary balance={sumBalance} monthly="£430"/>

Here’s my MongoDB schema to be totally clear - I want to take the ‘balance’ from this, which I thought would be this.state.debts.balance, and so previousValue.balance in my function:

const SubmitDebtSchema = new Schema ({
  creditCard: String,
  personalLoan: String,
  provider: String,
  balance: Number,
  limit: Number,
  monthly: Number,
  interest: Number,
  borrowed: Number
});

Here’s my full component code:

class IndividualDebts extends Component {
  constructor(props) {
    super(props)

    this.state = {
      debts: []
    }

  }

  componentDidMount() {
    axios.get("/api/fetchDebtCards")
    .then((response) => {
      this.setState({ debts: response.data })
    })
    .catch(e => {
      console.log(e)
    })
  }

  render() {

        const sumBalance = this.state.debts.reduce(function(previousValue, currentValue) {
          return (
            previousValue.balance + currentValue.balance
          )
        }, 0)

    return (
      <div>

            <IndividualDebtSummary balance={sumBalance} monthly="£430"/>

    </div>
        )
      }
    }

For reference - I have a separate ‘fetchDebts’ function and they render using ‘map’ - but I’ve not included them to keep the code a bit shorter.

Thanks, any help would be great.

Have you tried

const sumBalance = this.state.debts.reduce(function(previousValue, currentValue) {
          return (
            previousValue + currentValue.balance
          )
        }, 0)

From what I can tell previous value is a number not an object yet you are treating it like an object

1 Like

You’ve got it! Thank you so much… I knew it was something like that, just missed it. Have a great day!

1 Like