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,
};
}
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')
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With