Home > Blockchain >  Uncaught ReferenceError: Cannot access 'allNewDice' before initialization.... reactjs useS
Uncaught ReferenceError: Cannot access 'allNewDice' before initialization.... reactjs useS

Time:12-21

Hi friends:::: Need Help::: im trying to write code but i got a message :::::: Uncaught ReferenceError: Cannot access 'allNewDice' before initialization.... anyone can help me to solve this....please

import "./Main.css";
import Dices from "../Dices/Dices";
import React from "react";
const Main = () => {
  const [dice, setDice] = React.useState(allNewDice());

  const allNewDice = () => {
    const newDice = [];
    for (let index = 0; index < 10; index  ) {
      const randomNumber = Math.ceil(Math.random() * 6);
      newDice.push(randomNumber);
    }
    return newDice;
  };

  const rollDice = () => {
     setDice(allNewDice());
  }
  const diceElement = dice.map((die) => {
    <Dices value={die} />;
  });


  return (
    <main>
      <div className="dice-container">{diceElement}</div>
      <button onClick={rollDice}>Roll</button>
    </main>
  );
};

export default Main;

.....................

import "./Dices.css";

const Dices = (props) => {
  return <div className="dice"> {props.value} </div>;
};

export default Dices;

CodePudding user response:

The error tells you: Cannot access 'allNewDice' before initialization. You need to initialize and declare the allNewDice function before calling it.

// * Initializing allNewDice
const allNewDice = () => {
  const newDice = [];
  for (let index = 0; index < 10; index  ) {
    const randomNumber = Math.ceil(Math.random() * 6);
    newDice.push(randomNumber);
  }
  return newDice;
};  

// * Calling allNewDice()
const [dice, setDice] = React.useState(allNewDice());

CodePudding user response:

The allNewDice function is defined after it is called in the initial value for the dice state.

To fix this error, you can call the function inside the expression that is passed as the initial value for the state:

const [dice, setDice] = React.useState((() => allNewDice())());

Hope this helps.

  • Related