how to accumulate values within a map function and store in useState

Viewed 204

I have a map function which maps an array object of users with attributes fullname and points. Is there a way I can somehow add the points of every user whilst it maps and store it in a variable. I tried several ways with useState (in react), but I kept getting re-render error.

{users.map((user, index) => { return (
<tr key={index}>
  <td>{user.fullname}</td>
  <td>{user.points}</td>
</tr>
); })}

Any help would be appreciated..

2 Answers

I would do it in two separate steps. Collect the points

const totalPoints = users.
    map(user => user.points).
    reduce((a,b)=> a + b, 0)

then leverage it in your code.

 { totalPoints }

In the UI / Browser it isn't likley to have too much data to be able to perform this with multiple loops, and IMO it keeps the code cleaner.

You should set points for every user using foreach in another method.

const Method=()=>{
const list=  users.forEach(function(user){
  user.point= 10;
    });
    setUsers(list);
    }
Related