Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

How to pass data between +page.svelte and the respective +page.server in Sveltekit

$
0
0

Here is the scenario:

I have a +page.svelte file which is render the data for me. I have a +page.server file for that. In the +page.server I'm fetching some data from an endpoint. The fetch request in the server side depends on a number which should come from the client side. I mean the user enter a number into the input fielt, the clinet side should pass it to the +page.server file and then the serverside should perform the request and send the result to the client.

Here is the code for +page.server:

export const load = async ({ url}) => {    const pageNumber = url.searchParams.get('q');    const fetchData = async (pageNumber) => {        const productData = await fetch(`https://fakestoreapi.com/products/${pageNumber}`);        const products = await productData.json();        return products;    };    const data = await fetchData(pageNumber);    return {        dataFromAPI: data    };};

And here is the code for my +page.svelte:

<script>    import { goto } from '$app/navigation';    export let data;    let q = '';    const handleInput = (event) => {        q = event.target.value;        updateUrl();    };    const updateUrl = () => {        const url = new URL(window.location.href);        url.searchParams.set('q', q);        goto(url);    };</script><input    type="text"    name="search"    placeholder="Search something..."    on:input={handleInput}    bind:value={q}/>

Now, my question is:Is my approach valid and standard? Are there any specific capabilities that SvelteKit might offer for this? I assume there should be a more elegant approach than using URLs.I don't want to make any request in the client side, everything should be handled in the serverside.


Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>