import React from 'react';
import ReactDOM from 'react-dom';
import { useState } from 'react';
const Dice = () => {
const [dice, setDice] = useState([1, 1, 2, 2]);
function rollDice() {
return Array.from({length: 4}, () => Math.floor(Math.random() * 6) + 1);
}
const handleClick = () => {
setDice(rollDice());
}
const rolls = dice.map(die => <span> {die} </span> );
const stat = dice.splice(Math.min(...dice)).reduce(function(a, b) {
return a + b;
});
return (
<>
<button onClick={handleClick}>Roll for stats</button>
<div>
Your rolls are: {rolls}
</div>
<div>
Your stat is: {stat}
</div>
</>
);
}
export default Dice;
if (document.getElementById('dice')) {
ReactDOM.render(<Dice />, document.getElementById('dice'));
}
So I’m making online DnD and I’m testing out the dice rolls for stats, first few iterations went fine and then it returned the sum of the wrong numbers, it "randomly" removes the numbers I need and returns the wrong sum. I am doing this after being away from the code world for awhile so I’m sorry if it’s something dumb but i really can’t figure out what’s the issue.
3
Answers
This does the trick, changing stat to a function and running the splice method on a copy of the dice array:
and returning it as a function:
Thank you for all your help!
You can use reduce for this
you can try es6 syntax, extension operator(…)