I am trying to set up a standalone endpoint and then loop through it on a svelte page.
The console says it doesn’t recognize "phones" as an object but when I log it out it looks like an object. I am stuck. Thanks in advance for any assistance.
Code below.
page/__data.json:
{"phones":[{"id":1,"name":"iphone","price":123},{"id":2,"name":"iphone2","price":1234}]}
standalone.svelte:
<script context="module">
export const load = async ({ fetch }) => {
const res = await fetch("page/__data.json", {
headers: {
"Accept": "application/json"
}
});
const phones = await res.json();
return {
props: {
phones
}
}
}
</script>
<script>
export let phones;
</script>
{#each phones as phone}
{phone.name}<br>
{phone.price}<br>
{/each}
>Solution :
If that object is what you get from fetch, your code should probably be:
const { phones } = await res.json();
// or
const json = await res.json();
const phones = json.phones;