I'm providing you the code below, deleting tables(which are buttons) is not working as i want it to be. Even if it works randomly it messes up the array order and table names get messed up. What am i doing wrong
as i explained things get messed when i try to delete tables.
What im trying to do is add Button adds a table(a button), i will add the normal functionality later for now it just logs the clicked tables id. When delete mode is true i want the table that is clicked to delete itself.
<script>
let tables = [];
let deleteMode = false;
let tableCounter = 0;
function toggleDeleteMode() {
deleteMode = !deleteMode;
}
function tableClick(id) {
if(!deleteMode){
// this is a placeholder for the table click event
console.log(`Table with id ${id} was clicked`);
}
else{
tableCounter--
const tableIndex = tables.findIndex(table => table.id === id);
tables.splice(tableIndex, 1);
}
}
function createTable() {
tableCounter ;
const table = {
id: tableCounter,
name: "Table" tableCounter
}
tables = [...tables, table]
}
</script>
<div id="table-container">
<button on:click={toggleDeleteMode}>Delete Mode</button>
{#each tables as table, id}
<button on:click={tableClick(table.id)} class={!deleteMode ? "table" : "tableDelete"} >{table.name}</button>
{/each}
<button on:click={createTable} type="button"> </button>
</div>
<style>
#table-container {
display: grid;
grid-template-columns: repeat(auto-fill, 200px);
padding: 24px;
gap: 24px;
}
.tableDelete{
background-color: red;
height: 200px;
box-sizing: border-box;
padding: 16px;
border: none;
border-radius: 10px;
box-shadow: 0 0 7px rgba(0, 0, 0, 0.15);
resize: none;
font-family: sans-serif;
font-size: 16px;
}
.table {
height: 200px;
box-sizing: border-box;
padding: 16px;
border: none;
border-radius: 10px;
box-shadow: 0 0 7px rgba(0, 0, 0, 0.15);
resize: none;
font-family: sans-serif;
font-size: 16px;
}
.add-table {
height: 200px;
border: none;
outline: none;
background: rgba(0, 0, 0, 0.1);
border-radius: 10px;
font-size: 120px;
color: rgba(0, 0, 0, 0.5);
cursor: pointer;
transition: background 0.2s;
}
.add-table:hover {
background: rgba(0, 0, 0, 0.2);
}
</style>
CodePudding user response:
on:click={tableClick(table.id)}
should be on:click={() => tableClick(table.id)}
and you're missing that 'Assignments are reactive'
So you can either add the assignment of tables
to itself after the modification
const tableIndex = tables.findIndex(table => table.id === id);
tables.splice(tableIndex, 1);
tables = tables
or do it with this line
tables = tables.filter(table => table.id !== id )
With the 'counter-id' method it's quite easy produce duplicate ids after deleting items.
Here
{#each tables as table, id}
id
is actually the index, named id
. If you want to use the id as key (tutorial) it should be
{#each tables as table (table.id)}
which then will result in an error if there are multiple items with the same id. An alternative way to create one would be for example randomUUID