P5.js Undo Tool

Hello,
I hope everyone is doing well.

I’m trying to create an undo tool using P5.js.
I’m using a constructor function to make the tool.
What should I add to this function below? I want the undo button to work shapes.

Thank you

select("#undoButton").mouseClicked(function(){
         
     
    });

Pretend you are the undo button. When you get clicked, your job is to remove the last change made.

How are you going to know what the last change was?!? You will need some way to remember what the last shape added was, right? So you will need a data structure that tracks every shape that was added (and the shapes properties, probably), in order.

Using such a structure might also be useful for drawing the shapes.

Then, when you need to undo the last shape, you simply don’t draw the last one!

I wrote this button, but I can’t get it to work.

select("#undoButton").mouseClicked(function(){

        let previousState;

	let stateIndex = 0;

	this.setup = function() {
	// createCanvas(400, 400);
	background(255);
	saveState();
	}


	this.keyPressed = function(e) {
	// check if the event parameter (e) has Z (keycode 90) and ctrl or cmnd
	if (e.keyCode == 90 && (e.ctrlKey || e.metaKey)) {
	undoToPreviousState();
	}
	}

	function undoToPreviousState() {
	// if previousState doesn't exist ie is null
	// return without doing anything
	if (!previousState) {
	return;
	}
	// else draw the background (in this case white)
	// and draw the previous state
	background(255);
	image(previousState, 0, 0);
	// then set previous state to null
	previousState = null;
	}

	this.mousePressed = function() {
	// the moment input is detect save the state
	saveState();
	}

	function saveState() {
	// save state by taking image of background
	// for more info look at reference for get
	previousState = get();
	}
	});

Check this video below

https://www.awesomescreenshot.com/video/10142066?key=2a27591c515e5e0daa1f50f77589310a