The code below is supposed to generate 5 random indexes from an array, but I’m getting an infinite loop based on what I see in my console and it crashes the browser everytime. From my long hours of debugging, I realized it’s the matches.length
line in the while loop
that’s causing it. Any help on how to fix it will be much appreciated. Thank you.
const API_URL = 'http://127.0.0.1:8000/api/matches/';
/*
This is an async function that fetches matches from an API, generates a random selection of 5 matches,
sets the selection to state, and updates the UI accordingly, while handling any errors that may occur.
*/
async function generateRandomMatches() {
try {
const response = await axios.get(API_URL);
const matches = await response.data;
const newMatches: number[] = [];
// The code generates a list of 5 unique random indexes between 0 and the length of matches array.
while (newMatches.length < 5) {
const randomIndex: number = Math.floor(Math.random() * matches.length);
if (!newMatches.includes(randomIndex)) {
newMatches.push(randomIndex);
}
}
setSelectedMatches(newMatches);
setShowMatches(true);
} catch (error) {
console.error(error);
}
}
2
Answers
I wrapped the entire while loop in an
if-else
condition. Like soYou are going after
matches.length
then the while loop conditions is wrong.Think if
matches
containe 3 items then the while loop will never gets more then 3 and you are checkingnewMatches.length < 5
.That is why the while loop never resolve.
I added a fix by modifying the condition to
newMatches.length != matches.length
this should solve the issue.