Using a form variable for filtering a database

59 Views Asked by At

This is my code in my +page.server.js:

export const actions = {
    default: async ({request}) => {
        const data = await request.formData();
        const ln = data.get('lastname');
    .....
    }
};

export function load() {
    if (!db) throw error(404);

    return {
        todos: db.getTodos()
    }
}

My question: how do I use the actions object output variable for filtering what I get from db.getTodos() in the load function?

I can implement the filter on the front-end in +page.svelte by using a bind:value on the variable, but I would rather filter on the server side.

1

There are 1 best solutions below

7
brunnerh On BEST ANSWER

The easiest way to return the correct results would be to just return them directly via the form action's data. If you want to use load, there are three options I can think of:

  • Redirect to a URL containing the information necessary to filter
  • Pass the data via a cookie
  • Store the information server-side in a user session

I would not really recommend the latter two options, as they make things stateful and thus more messy.

For the redirect you can use query parameters or a different route with route parameters.
Here would be a simple example using the current route & query parameters:

// +page.server.js
import { fail, redirect } from '@sveltejs/kit';
import { findResults, findId } from './db.js';

export const load = async ({ url }) => {
    const id = url.searchParams.get('id');
    const results = id == null ? null : await findResults(id);

    return { results };
};

export const actions = {
    default: async ({ request }) => {
        const formData = await request.formData();
        const name = formData.get('name');
        const id = await findId(name);

        if (id == null)
            return fail(404, { error: 'Not Found' });

        const newUrl = new URL(request.url);
        newUrl.searchParams.set('id', id);

        redirect(302, newUrl); // throw in SvelteKit v1
    }
};
<!-- +page.svelte -->
<script>
    import { enhance } from '$app/forms';
    
    export let data;
    export let form;
</script>

<form method="post" use:enhance>
    <label>
        Search by name<br/>
        <input type="text" name="name" />
    </label>
    <button>Submit</button>
</form>

{#if form?.error}
    <p style="color: red">{form.error}</p>
{/if}

{#if data.results}
    <!-- results for search here -->
{/if}