Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass props to a SvelteKit endpoint

I am trying to pass props to an SvelteKit endpoint async function with no success. I'm using a store to pass value, but for reasons I don't understand value is undefined when I try to get it within the function.

Can anyone see what I'm doing wrong, either accessing the store value or if there is a better way to pass value to the function? Thanks! Eric

index.svelte

<script lang="ts">
  
  import { sampleData } from "~/data/sample";

  async function handleClick() {
    $sampleData = {value: "Fancy"};
    const result = await (await fetch(`/apis/ping`)).json();
    console.log("result", result);
  }
</script>


<button on:click={handleClick}>Ping</button>
ping.ts

import { sampleData } from "~/data/sample";
import { get as getDoc } from "svelte/store";


export async function get(): Promise<{ body: any }> {

  const _sampleData = getDoc(sampleData);
  const value = _sampleData.value;
  console.log("value", value);  

  // const value = "Fancy";

  const result = await (
    await fetch(`https://my-server/app/ping?value=${value}`)
  ).json();

  console.log("result", result);

  return {
    body: result,
  };
}
like image 337
JarvisWorks Avatar asked Sep 19 '25 21:09

JarvisWorks


2 Answers

Stores are not shared between server and client, so the store in the endpoint will still be it's initial value (undefined in your case)

You have to see the frontend (what is executed on the browser) and the backend or endpoints (executed on the server) as something completely seperate.

That said, you should pass the parameters together with the fetch, either in the body or as queryparameters.

in body

// in the client
fetch('/apis/ping', {
  body: JSON.stringify({ value: "Fancy" }),
  headers: {
    'Content-Type': 'application/json'
  }
})
// in the endpoint
export async function get({ body }) {
  const sampleData = body;
}

as query parameters

// in the client
fetch('/apis/ping/?value=Fancy')
// in the endpoint
export async function get({ query }) {
  const sampleData = query.get('value')
}
like image 81
Stephane Vanraes Avatar answered Sep 23 '25 11:09

Stephane Vanraes


Here is what ended up working for me:

index.svelte

<script lang="ts">
  const value = "Fancy";
  async function handleClick() {
    let response = await(await fetch(`/apis/ping/?value=${value}`)).json();
    console.log("response", response);
  }
</script>


<button on:click={handleClick}>Ping</button>

ping.ts

export async function get({ query }) {
  const value = query.get("value");
  const result = await (await fetch(`https://my-server/app/ping?value=${value}`)).json();

  return {
    body: result,
  };
}

Not sure why wrapping in additional awaits and coercing to json was necessary

like image 41
JarvisWorks Avatar answered Sep 23 '25 13:09

JarvisWorks