Home > Back-end >  How to pass data from sveltekit route to shadow endpoint .ts
How to pass data from sveltekit route to shadow endpoint .ts

Time:06-19

I have my file structure in a sveltekit app like this:
src/routes/test/sample.svelte

<script>
    export let message;
    postId = 64;
</script>

<h1>{message}</h1>

src/routes/test/sample.ts

let postId;
export async function get() {
    return {
        body: {
            message: 'Selected post id is : '   postId ,
            
        }
    };
}

With this code we can get message from .ts file and show it in .svelte route;
How can I pass postId from sample.svelte into sample.ts ?

CodePudding user response:

To pass parameters onto an endpoint you have some freedom for how you want to specify them.
What you would always need to do is a fetch request, with the post id somehow included in that request.

I'd recommend passing the post id as a path parameter. That would entail changing the filename for your endpoint to src/routes/test/sample/[postId].ts or something similar, and then fetching directly like this:

const result = await fetch(`./sample/${postId}`);

This fetch would have to be done during the load function of that page.
However for simple cases like this, you can also just have both the page and the endpoint have the same name (as in src/routes/test/sample/[postId].svelte and src/routes/test/sample/[postId].ts), and the props of the page will be populated with the response from the endpoint.
Much simpler, and probably the better option for you.

To then get the postId inside the endpoint, you can use the params object that is being passed to it. When you have a expression such as [postId] in your endpoints path, then params.postId will be populated with the string in that position in the path, when the endpoint is being requested.
A completed endpoint for you might look something like this:

export async function get({params}) {
  const postId = params.postId
  return {
    body: {
      message: 'Selected post id is : '   postId ,
    }
  };
}

Also all of this is listed in the documentation of svelte kit, which is over all quite good. Have a look at the pages about endpoints.

  • Related