I receive the following errors when using the removeData function in the code below.
Alpine Expression Error: Cannot read properties of undefined (reading 'name')
Expression: "data[id].name"
<input x-model="data[id].name" type="text" name="name"></input>
Alpine Expression Error: Cannot read properties of undefined (reading 'text')
Expression: "data[id].text"
<input x-model="data[id].text" type="text" name="text"></input>
Everything appears to work correctly but the error message is generated in the console. Is there a way to stop this from happening?
function handler() {
return {
data: {},
getData() {
console.log(this.data);
},
addData() {
x = Object.keys(this.data);
x = x.map(function(x) {
return parseInt(x, 10);
}).sort();
n = x[x.length - 1];
if (isNaN(n)) {
n = 0;
};
this.data[n + 1] = {
'name': '',
'text': ''
}
},
removeData(id) {
delete this.data[id];
},
}
}
<script src="//unpkg.com/alpinejs" defer></script>
<div x-data="handler()">
<button type="button" @click="getData()">ShowData</button>
<button type="button" @click="addData()">AddData</button>
<template x-for="[id, value] in Object.entries(data)" :key="id">
<div :id="id">
<input x-model="id" type="number">
<input x-model="data[id].name" type="text" name="name">
<input x-model="data[id].text" type="text" name="text">
<button type="button" @click="removeData(id)">Remove</button>
</div>
</template>
</div>
If you correct the following, you will find the cause.
this.data[n + 1] = {
//+
'name': `${n+1}taro`,
'text': `${n+1}taro san shibakariheitta`
}
},
//+
<pre x-text="JSON.stringify(data, null, 2)"></pre>
How about the following as a solution?
//+
<input x-model="value.name" type="text" name="name">
<input x-model="value.text" type="text" name="text">