I have this code snippet. It’s a bit long but that’s the shortest I could make it to reproduce the error.
The idea is to have a data
variable which displays selected data and a template
object from which the user can select entries which should be added to data
.
When I select the values from the three drop downs and click “add” it works the first time. But when I repeat it the second time I get this error:
Alpine Expression Error: Cannot read properties of undefined (reading '')
Expression: "Object.keys (template[select.a][select.b])"
<template x-for="i in Object.keys (template[select.a][select.b])" :key="i">...</template>
Uncaught TypeError: Cannot read properties of undefined (reading '')
at [Alpine] Object.keys (template[select.a][select.b]) (eval at <anonymous> (https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js:5:665), <anonymous>:3:63)
...
But on line 44
and 53
I have x-if directives to check if select.a
and select.b
is != ''
. This should prevent the following code from being executed/rendered at all. Is this a bug in alpine or do I make something wrong?
<html>
<head>
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>
<script>
function App() {
return {
template: {
a: {
b: {
c: 1
}
},
},
data: [],
select: {
a: '',
b: '',
c: '',
},
add: function () {
this.data.push (this.template[this.select.a][this.select.b][this.select.c]);
this.select = {
a: '',
b: '',
c: '',
};
}
};
}
</script>
</head>
<body x-data="App()">
data: <div x-html="JSON.stringify (data)"></div>
<div>
<select x-model="select.a">
<option disabled selected="selected" value="">choose</option>
<template x-for="i in Object.keys (template)" :key="i">
<option :value="i" x-html="i"></option>
</template>
</select>
<template x-if="select.a != ''">
<div>
<select x-model="select.b">
<option disabled selected="selected" value="">choose</option>
<template x-for="i in Object.keys (template[select.a])" :key="i">
<option :value="i" x-html="i"></option>
</template>
</select>
<template x-if="select.b != ''">
<div>
<select x-model="select.c">
<option disabled selected="selected" value="">choose</option>
<template x-for="i in Object.keys (template[select.a][select.b])" :key="i">
<option :value="i" x-html="i"></option>
</template>
</select>
<template x-if="select.c != ''">
<button @click="add()">add</button>
</template>
</div>
</template>
</div>
</template>
</div>
</body>
</html>