1

Problem : I am trying to create an array of 4 things from a list but the while loop always produces an infinite loop.

const [options, setOptions] = useState([]);

const getThings = () => {
     while(options.length < 4) {
          let randomThing = 
listOfThings[Math.floor(Math.random()*listOfThings.length)];

     !options.includes(randomThing) && setOptions([...options, randomThing]);
    }
};

I believe the problem is connected to another issue - when I call the function once, it is randomly called anywhere between 2 - 9 times even without the while loop attached. Still trying to figure out why it keeps randomly firing so much.

getThings();
Bryan F
  • 49
  • 4

2 Answers2

4

setState does not instantly change any values. Create the entire array first, then set the state at the end of the loop.

const getThings = () => {
    let newOptions = [...options];
    while (newOptions.length < 4) {
        let randomThing = listOfThings[Math.floor(Math.random()*listOfThings.length)];
        if (!newOptions.includes(randomThing)) newOptions.push(randomThing);
    }
    setOptions(newOptions);
};
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

The error is caused because you are calling setOptions inside a loop, you could cache a new output in the function and then call the hook at the end

https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level

Mario Perez
  • 2,777
  • 1
  • 12
  • 21