import React, {Component} from 'react';

interface FixedState {
    color: string
}

class Fixed extends Component<{}, FixedState> {

    canvasRef: any

    constructor(props: {}) {
        super(props);
        this.canvasRef = React.createRef();
        this.state = {
            color: "purple"
        };
    }

    componentDidMount() {
        // This is only necessary if you want the purple rectangle
        // to show up at the beginning.
        this.drawSquare();
    }

    componentDidUpdate() {
        // Instead, only use state when we've been notified that an update has happened.
        this.drawSquare();
    }

    drawSquare() {
        let context = this.canvasRef.current.getContext("2d");
        context.fillStyle = this.state.color;
        context.fillRect(10, 10, 180, 180);
    }

    setGreen = () => {
        this.setState({
            color: "green"
        });
        // Don't try to use state right after you've requested to update it.
    };

    setRed = () => {
        this.setState({
            color: "red"
        });
        // Don't try to use state right after you've requested to update it.
    };

    setBlue = () => {
        this.setState({
            color: "blue"
        });
        // Don't try to use state right after you've requested to update it.
    };

    render() {
        return (
            <div>
                <p>Current Color: {this.state.color}</p>
                <button onClick={this.setGreen}>Green</button>
                <button onClick={this.setRed}>Red</button>
                <button onClick={this.setBlue}>Blue</button>
                <br/>
                <canvas ref={this.canvasRef} width="200" height="200"></canvas>
            </div>
        );
    }

}

export default Fixed;
