Can't write to array

Viewed 140

I'm trying to use react to build a sorting visualizer. When I try to update the array, in line number 31 it won't update for some reason. But when I log it to the console, the updated array is logged.

import React, { useState, useEffect } from "react";
import "./SortingVisualizer.css";
const SortingVisualizer = () => {
    const [getArray, setArray] = useState([]);
    useEffect(() => {
        resetArray(20);
    }, []);

    const resetArray = size => {
        const array = [];
        for (let i = 0; i < size; i++) {
            array.push(randomInt(20, 800));
        }
        setArray(array);
    };

    const bubbleSort = () => {
        let temp,
            array = getArray;
        /*for (let i = 0; i < array.length; i++) {
            for (let j = 0; j < i - 2; j++) {
                if (array[j] > array[j + 1]) {
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
    }*/
        array = getArray;
        array[3] = 3;
        setArray(array);
        console.log(array);
    };
    return (
        <>
            <div className="menu">
                <button onClick={() => resetArray(20)}>Geneate new array</button>
                <button onClick={bubbleSort}>Do bubble sort</button>
            </div>
            <div className="array-container">
                {getArray.map((value, i) => (
                    <div
                        className="array-bar"
                        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;
2 Answers

As pointed out by several users, what I did was 'Mutating stats', which means that I assigned the getArray to the array variable, but they were referencing the same object. So what I did to solve the problem, is let array = Object.assign([], getArray); That created a copy of the object as I intended, and not just another reference.

This is not the right way of updating the state. You should be using the spread operator ( ... ) while updating an array or object.

For instance:

getArray([...3]);

Related