Important! This is not a problem with an async API!
I have this attempt to create a bubble sort visualizer, and when I run the algorithem
itself, I want the user to actually see it in action.
So each time I make a swap I want the user to be able to see it happens.
When the loop inside the bubbleSort runs, and updates the states Classes and Array, nothing happens, until the loop completely ends.
If I put a break; in the loop, react renders when the loop stops.
What is the problem? How can I fix it?
EDIT:
If you have an answer, please explain why it works, and how I shoul dimplement it in my code.
import React, { useState, useEffect } from "react";
import "./SortingVisualizer.css";
import { render } from "@testing-library/react";
const SortingVisualizer = () => {
const [getArray, setArray] = useState([]);
const [getClasses, setClasses] = useState([""]);
useEffect(() => {
resetArray(200);
}, []);
useEffect(() => {}, [getArray, getClasses]);
const resetArray = size => {
const array = [];
const classesArray = [];
for (let i = 0; i < size; i++) {
array.push(randomInt(20, 800));
classesArray.push("array-bar");
}
setArray(array);
setClasses(classesArray);
};
const bubbleSort = delay => {
let temp,
array = Object.assign([], getArray),
classes = Object.assign([], getClasses);
for (let i = array.length; i > 0; i--) {
for (let j = 0; j < i - 1; j++) {
classes[j] = "array-bar compared-bar";
classes[j + 1] = "array-bar compared-bar";
if (array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
//console.log((array.length - i) * 200 + (j + 1));
setArray(array);
setClasses(classes);
break;
}
}
console.log("done.");
};
return (
<>
<div className="menu">
<button onClick={() => resetArray(200)}>Geneate new array</button>
<button onClick={bubbleSort}>Do bubble sort</button>
</div>
<div className="array-container">
{getArray.map((value, i) => (
<div
className={getClasses[i]}
key={i}
style={{ height: `${value * 0.1}vh` }}
></div>
))}
</div>
</>
);
};
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
export default SortingVisualizer;