Search code examples
routesdynamicsveltesluggoto

Svelte goto using slug


I'm using svelte for a personnal project and i'm wondering if someone has the trick to do that.

I've a list of blog pages and for each pages i've a next_page and previous_page url The problem is:

from the url /blog/[blogname]

with next_page = "/blog/[nextblogname]" previous_page = "/blog/[previousblogname]"

the href or goto function change the url to the right one but never trigger the +page.js execution that load the right blog content with the api call

I guess i missed something in the dynamic routing setup ?

Thanks in advance !

i tried:

+page.svelte

<a href="/blog/2">
    next page
</a>

+page.server.js / +page.js

<script>
    import { goto } from '$app/navigation';
    function next_page() {
        goto("/blog/2");
        // also tested goto("/blog/2", {replaceState: true});
    }
</script>
<div on:click={() => next_page()}>
    next page
</div>

I also tried to load everything from the .svelte file but it's also not working

I tried to create a component on which you give the blog infos but the .svelte dont refresh

Progress: I changed the +page.js into +page.server.js and new blog infos are loaded server side, but client side the page don't refresh and don't display/catch the new blog informations

I also tried:

+page.js

import component from "./blog_content.svelte";
export function load({ fetch, params}){

    // load my blog content

    return {
        blog_data: data,
        component
    };
)

+page.svelte

{#if $page.data.component}
    <svelte:component this={$page.data.component} blog_data={blog_data}/>
{/if}

But it changes nothing

if i try to change the page.js into page.server.js it says

Error: Data returned from 'load' while rendering /blog/[blogId] is not serializable: Cannot stringify a function


Solution

  • Just as the error states: You cannot serialize a function (in this case a component).

    If you want to dynamically change what component is being displayed, you have to approach that differently, e.g. only send a component name and resolve that on the page.

    In most cases that should not be necessary at all, in your example you always send the same component anyway. Just import that on the page and use it directly.

    <BlogContent {blog_data} />