Search code examples
fetch-apisveltesveltekit

SvelteKit - API fetches data correctly in javascript but UI fails to render it


+page.svelte:

<script>
    import { onMount } from 'svelte';

    let careers = [];

    const fetchCareers = async () => {
        const apiUrl = 'http://localhost:4000/api/v1/careers';

        try {
            const response = await fetch(apiUrl);

            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }

            const data = await response.json();

            careers = data;

            console.log('Updated careers:', careers);
        } catch (error) {
            console.error('Error fetching careers:', error.message);
            console.error(error);
        }
    };

    onMount(fetchCareers);
</script>

<h1>Careers</h1>

{#if careers.length > 0}
    {#each careers as career (career.id)}
        <p>{career.name}</p>
    {/each}
{:else}
    <p>Failed to load careers...</p>
{/if}

Image - Browser console fetches data

careers.length seems to be undefined. Wondering if I am using my if else block incorrectly? I thought this may be a CORS issue with my API but I am able to get my POST function working so I'm unsure why the names aren't being rendered correctly in the browser?


Solution

  • The screenshot shows that the data has a different shape than what your code is assuming.

    The items end up in careers.data not directly in careers.