0

I want my function to roll 5 dices and store them in my dices state.

In the recent version, i am only storing one object for the next click, but i made the for loop to generate 5 dices at once, how can i store the previous dce object(s) for the next iteration in the for loop?

import './App.css';
import Subgroup from './Subgroup'
import React, {useState} from 'react'


function App() {

  const [numberRolls, setNumberRolls] = useState(3);
  const [dices, setDices] = useState([]);


  return (
    <div className="App">
        <Subgroup 
          numberRolls = {numberRolls}
          setNumberRolls = {setNumberRolls}
          dices = {dices} 
          setDices = {setDices}
        />
    </div>
  );
}

export default App;
import React from 'react'


const Subgroup = ({numberRolls, setNumberRolls, dices, setDices}) => {

    const rollTheDice =  () => {
        if(numberRolls > 0) {
            setNumberRolls(numberRolls - 1);

            for(let i = 0; i < 5; i++) {
                setDices([...dices,                 // i think sth should be different here????
                    {id: Math.random()*100, 
                     number: Math.ceil(Math.random()*6)-1, 
                     selected: false} 
                ])
            }
        }
        console.log(dices)
    }

    return (
        <div> 
            <button onClick={ rollTheDice }>blablabala </button>
        </div>
    )
}

export default Subgroup;

1 Answer 1

1

Try saving the result in an array, then set the state, something like:

const result = [];

for(let i = 0; i < 5; i++) {
  result.push({
    id: Math.random() * 100, 
    number: Math.ceil(Math.random() * 6) -1, 
    selected: false
  });
}
  
setDices(prev => [...prev, ...result]);
Sign up to request clarification or add additional context in comments.

1 Comment

oh wow that was not that hard, thank you!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.