Adam Ashkenazy
Adam Ashkenazy

Reputation: 49

SvelteKit: Type Issues with Data Loading

I am having trouble understanding how to properly load data to my page. Here is my current project structure:

src/
├── components/
│   └── Post.svelte
└── routes/
    ├── +page.svelte
    ├── +page.server.js
    └── +layout.svelte

I am trying to load data to +page.svelte using the load function in +page.server.js and send it to Post.svelte. I am using +page.server.js because I load the data from a Firebase Real-Time database. However, when I load the data from page.server.js and try to access the post field, I get an error saying that the field is not in the JSON.

Here are the relevant code snippets:

+page.server.js

Currently, this page returns the same basic JSON. Note that I am using the PageServerLoad type because I am using +page.server.js instead of +page.js.

/** @type {import('./$types').PageServerLoad} */
export function load({ params }) {
  return {
    post: {
      "quote": "Something quote",
      "description": "Something description"
    }
  };
}

+page.svelte

<script>
    import Post from '../components/Post.svelte'
    /** @type {import('./$types').PageData} */
    export let data;
</script>

<h1>Lyrics and Quotes</h1>
<Post postData={data.post}/> // Error here: property 'post' does not exist in '{}'.

+Post.svelte

<script>
    /** @type {import('../routes/$types').PageData} */
    export let postData;
</script>

<p>
    This is a post.
    {postData.quote} //Error here: property 'quote' does not exist in '{}'.
</p>

Upvotes: 2

Views: 3104

Answers (1)

Tholle
Tholle

Reputation: 112777

/** @type {import('./$types').PageData} */ results in the type { post: { quote: string; description: string; }; }, so you must make sure to pick the post property:

<script>
    /** @type {import('../routes/$types').PageData["post"]} */
    export let postData;
</script>

<p>
    This is a post.
    {postData.quote}
</p>

Upvotes: 3

Related Questions