How to render element each time state is updated

Viewed 53

I am trying to build a sorting visualizer using React. Right now I am implementing bubblesort and I want to see my array at each stage of the sort.

class Sorter extends Component {
    state = {
          array: [100,4,214,55,11,22,10,33],
    }
     bubblesorter = () => {
        let arr = this.state.array
        var len = arr.length,
        i, j, stop;
            for (i=0; i < len; i++){
                    for (j=0, stop=len-i; j < stop; j++){
                        if (arr[j] > arr[j+1]){
                            swap(arr, j, j+1);
                        } 
                        this.setState({array:arr})
                    }
                }   
    }

    render() {
        const array = this.state.array
        // console.log(array)
        return (
            <div>
                <h1>This is a sorter</h1>
                <div className="container">
                    {array.map((value, id) => (
                        <span>
                            <div className="bar" key={id} style={{height: value+"px"}}  >
                            </div>
                        </span>
                    ))}
                </div>
                <button onClick={this.bubblesorter}>Sort</button>
            </div>
        )
    }

Initially:
enter image description here

Immediately after clicking "sort":
enter image description here

Although I am using setState in inside the loop for each iteration, I only see the final sorted array. I would like to render the array for each step of the sorting (and possibly using a time delay). But I am not able to implement this.
Can someone please help on how to modify this code to implement such a functionality...Thanks

1 Answers

Oh, it actually changes(The execution time is so fast for the eyes to detect) and you will see it if you set some delay in your loop.

For example:

bubblesorter = async () => {
    let arr = this.state.array
    var len = arr.length,
        i, j, stop;
    for (i = 0; i < len; i++) {
        for (j = 0, stop = len - i; j < stop; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(arr, j, j + 1);
            }
            // Added 1 second delay here.
            await new Promise(resolve => setTimeout(resolve, 1000));
            this.setState({ array: arr })
        }
    }
}
Related