Hello guys,
I have a issue with x-for and a array of object.
I can't show different value from the same object in tag.
I probably doing something wrong but I don't fine any issue anywhere.
Maybe someone have a idea ?
<body x-data="application()" x-init="getApps()">
<section id="app" class="my-5">
<template x-for="app in listApps">
<div x-text="app.status"></div>
<div x-text="app.name"></div> <--- my problem is here
</template>
</section>
<script>
function application() {
return {
listApps: [],
index: 0,
getApps: async function () {
const response = await fetch('https://my-json-server.typicode.com/JonDelWeb/test_cyb/connection_extended');
const data = await response.json();
this.listApps = data;
}
}
}
</script>
</body>
</html>
I have this error in my console :
Alpine: <template> tag with [x-for] encountered with multiple element roots. Make sure <template> only has a single child element.
The warning is because template has 2 descendents, see here, you've got 2 div's
<template x-for="app in listApps">
<div x-text="app.status"></div>
<div x-text="app.name"></div> <--- my problem is here
</template>
to fix it you can do:
<template x-for="app in listApps">
<div>
<div x-text="app.status"></div>
<div x-text="app.name"></div> <--- my problem is here
</div>
</template>
Have you got any feedback on the warning that would have helped you fix it?
It might be worth adding a "Troubleshooting common errors" to the docs and link to it in the warnings, this is what projects like eg. Next.js/React do and it's super useful.
Yes, that's fix my issue, thanks a lot ! ;)
And yes too, that's would be great if the are a "Troubleshooting common errors" rapport to the docs.
And maybe in the warning add something like "The elements must be wrap in one" or something more explicit because a don't find anywhere in the docs how use x-for with a array of object and how showing many value.
But thanks for your answer ! I close it.
@JonDelWeb yeah "Make sure only has a single child element." seems obvious to us but not to everyone it seems 馃槃
Effectively... But once you know it, it's obvious ... Not before ! ;)
I think it mostly depends on how you would say that in your native language, so it's impossible to cover all cases.
"elements must be wrap in one" will probably sound weird to other users(one what? Which elements? Etc) and they might prefer a different wording, etc. The suggestion about "Troubleshooting common errors" is a good one, though.
Most helpful comment
@JonDelWeb yeah "Make sure only has a single child element." seems obvious to us but not to everyone it seems 馃槃