Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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.

like image 914
ShashComandur Avatar asked Aug 10 '26 00:08

ShashComandur


1 Answers

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

like image 111
H.B. Avatar answered Aug 12 '26 20:08

H.B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!