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

52 Views Asked by At

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.

1

There are 1 best solutions below

2
brunnerh On

Using a query parameter is fine, though you could add replaceState: true to the goto options to prevent growing the history stack unnecessarily and keepFocus should probably be set as well.

You could also use a form action (e.g. with use:enhance, though this needs adjustments to prevent form reset and loss of focus) instead, this means the URL would not need to change but then you also cannot refresh the page and trigger the same search.