Passing props via route Sveltekit

Viewed 4162

I am using Svelte+Sveltekit without any routing libraries.

What I would like to do is pass an object to a route, from another page via an <a> tag (or otherwise).

On one page I have a list of objects, for each object I render an item:

// home.svelte

<-- start of page -->
  {#each users as user}
    <a href="users/{user.username}" sveltekit:prefetch/>
  {/each}
<-- end of page -->

The user object above has a few key-value pairs I want to render in the /users/{username} - which is created as a slug route:

// routes/users/[slug].svelte

<script context="module">
  export async function load(ctx) {
   let data = ctx.page.params;

   // I'd like to be able to pass the whole user object from the <a> tag in home.svelte, and access it from ctx.page.params if possible
        
  return { props: { slug: data.slug, user: data.user } }
}
</script>
<script>
  export let slug;
  export let user; 
</script>

<div>
  <h1>{slug}</h1>
  <h1>{JSON.stringify(user)}</h1>
</div>

Is it possible to do it this way, or do I need a different approach/routing library?

2 Answers

I think it okay to do this. You can get the {user.username} in users/[slug].svelte by export the load function with 'page' parameter. You may try to modify it as below. You may check out the svelteKit online document here

export const load = ({ page }) => {
  var username = page.params.slug;  //slug refer to [slug].svelte
  return {
    props: {
      user: GetUserByName(username);
    }
  };

...

You can use the 'query' param

// home.svelte
//use a query string converter library

<a href="users/{user.username}?{objectToQuery(user)}" sveltekit:prefetch/>

then in load function

return { 
  props: { 
    slug: page.params.slug, 
    user: queryToObject(page.params.query) 
  } 
}

but your safest bet is to use a store.

<div>
  <h1>{slug}</h1>
  <h1>{JSON.stringify($user)}</h1>
</div>

In which case you dont need to pass anything.

Related