Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Empty parameters in SvelteKit load function

I’m trying to build a art portfolio in SvelteKit, following the SvelteKit tutorial. I have a page called art/, which has a subdirectory called [collections]/ for various different collections of art pieces.

I’m temporarily loading data from a file called data.js which has the following structure:

export const collections = [
    {
        title: 'Crisis Vision',
        id: 'crisis-vision',
        content: '<p>crisis vision content</p>'
    },

    {
        title: 'From the Garden',
        id: 'from-the-garden',
        content: '<p>from the garden content</p>'
    },
    
    {
        title: 'As Lost Through Collision',
        id: 'as-lost',
        content: '<p>as lost content</p>'
    }
]; 

The +page.server.js file in [collections]/ has the following contents:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { error } from '@sveltejs/kit';
import { collections } from '../data.js';

export function load( {params} ) {
    const ret = collections.find((c) => c.id === params.id);
    return { 
        ret 
    };
}

The +page.svelte file has the following contents:

<script>
    export let data;
    console.log(JSON.stringify(data))
</script>

<h1>{data.ret.title}</h1>
<div>{@html data.ret.content}</div>

When I try to run this, I get TypeError: Cannot read properties of undefined (reading 'title').

I believe I have narrowed this down to the params variable. When I take out params.id in the +page.server.js file, and directly replace it with an example from the data, say 'as-lost', it works as intended as shown here (granted, every collection shows the same content). When I add console.log(JSON.stringify(data)) to the script portion of the page file, it shows that the params object is empty.

What am I doing wrong here? I have tried to follow the tutorial at every step, and it’s still not working. Please help.

>Solution :

If you use [collections] in the route path, you also have to use params.collections.
(Maybe make that singular)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading