0

Goal:
Display the total sum of all id value after the text "Total sum of all id value is:"
The id value is from the API data.

Problem:
I do not know how to do it and is it possible to do it?

Info:
I'm a newbie in React JS

Stackblitz:
https://stackblitz.com/edit/react-f7chuv?

Thank you!


import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      data: null
    };
  }

  componentDidMount = () => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(res => res.json())
      .then(data => {
        this.setState(prevState => ({
          ...prevState,
          data
        }));
      });
  };

  render() {
    return (
      <div>
        <p>Start editing to see some magic happen :)</p>
        <ul>
          {this.state.data &&
            this.state.data.map(user => (
              <li key={user.id} id={user.id}>
                {user.id}
              </li>
            ))}
        </ul>
        <div>
          Total sum of all id value is: 
        </div>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));
HelloWorld1
  • 13,688
  • 28
  • 82
  • 145
  • your best bet is to use the js ```reduce()``` to get the sum and then put that value where you need it in your render method ```
    Total sum of all id value is: {this.state.data.reduce(what you want to sum here)}
    ```
    – Michael Jun 23 '21 at 21:02

3 Answers3

1

There are various ways this can be accomplished, but you need to effectively loop over the data array and accumulate/add the IDs up. You can do this with Array reduce:

Total sum of all id value is: {this.state.data && this.state.data.reduce((acc, curr) => acc + curr.id, 0)}

Another alternative is at the first line inside of render():

let idSum = 0;
for (let i = 0; this.state.data && i < this.state.data.length; i++) {
    idSum += this.state.data[i].id;
}

Then you can output the idSum:

Total sum of all id value is: {idSum}
Marc Baumbach
  • 10,323
  • 2
  • 30
  • 45
0

You can use map/reduce and display the result

      {this.state.data && (
        <>
          Total sum of all id value is:{' '}
          {this.state.data.map(itm => itm.id).reduce((a, b) => a + b, 0)}
        </>
      )}

stackblitz

Apostolos
  • 10,033
  • 5
  • 24
  • 39
  • It'd be better to store this in state instead of calculating it on every render. Also you don't need to map it before you reduce, just say `a + b.id` – Samathingamajig Jun 23 '21 at 21:05
0

Another possible solution would be to implement it in your then callback after the successful fetch.

Here's an adaptation of your component

import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      data: null,
      idSum: null // <========== HERE 
    };
  }

  componentDidMount = () => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(res => res.json())
      .then(data => {
        const idSum = data.reduce((tot, next) => tot + next.id, 0); // <========= HERE
        this.setState(prevState => ({
          ...prevState,
          data,
          idSum  // <========= HERE
        }));
      });
  };

  render() {
    return (
      <div>
        <p>Start editing to see some magic happen :)</p>
        <ul>
          {this.state.data &&
            this.state.data.map(user => (
              <li key={user.id} id={user.id}>
                {user.id}
              </li>
            ))}
        </ul>
        <div>
          Total sum of all id value is: {this.state.idSum}
        </div>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

You can find more info about reduce method here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Najt
  • 46
  • 3