I need to print in my list all the items of my array, but I'm getting only the last item printed. When I console.log it, I can see all the items. Not sure why this is happening, I tried to figure out using all I've got, but none worked.
let examples = [];
onMount(async () => {
const response = await fetch(
"https://<my-api>/db/v1/cosmos/{container}",
{
method: "POST",
headers: {
"<api-key>":
"<my-api-key>",
},
body: JSON.stringify({
query: "SELECT * FROM c ORDER BY c.name ASC",
}),
}
).then((response) => response.json());
for (let i = 0; i < response.data.length; i++) {
console.log(response.data[i].name);
examples = response.data[i].name;
}
});
On my HTML I'm using the following loop:
{#each examples as example}
<ListgroupItem class="text-base font-semibold gap-2">
Name: {examples} <br />
</ListgroupItem>
{/each}
What I'm getting in return, is just only the last item of my array. If I use example instead of examples, on my foreach loop, my return is only the letters.
When I'm using SvelteKit and Cosmos DB. Something I don't get is that if the item has 5 letters, it will print 5 rows. If another item has 7 letters, it will print 7 rows. Not sure why. I am not getting any error. Any ideas what I'm doing wrong? I also have tried using those below, but they didn't work.
examples.unshift(0);
examples.push(examples);
You are always assigning to what is supposed to be a list, the name of the current item, so at the end you are left with just the name of the last item:
for (let i = 0; i < response.data.length; i++) {
console.log(response.data[i].name);
examples = response.data[i].name;
}
If you only want a list of name this should be replaced with:
examples = response.data.map(x => x.name)
The #each
is also wrong, it iterates the variable but you are not using the item, but the list variable, it should be:
{#each examples as example}
<ListgroupItem class="text-base font-semibold gap-2">
Name: {example} <br /> <!-- example, not examples -->
</ListgroupItem>
{/each}
(As examples
was just a string before, it iterated the letters in the string.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.