:: krowemoh

Sunday | 29 DEC 2024
Posts Links Other About Now

previous
next

Svelte Snippets

2024-12-18

Some helpful snippets for svelte.

The svelte5 of getting props:

   let { data, form }  = $props();

Form error notifications:

   {#if form?.error}
      Error: {form.error}
   {/if}

A basic +page.server.js:

import { fail, redirect } from '@sveltejs/kit';
import { dbUpdate } from "$lib/dbActions.js";

export async function load({ locals, params }) {
    let userid = locals.session.data.userid;
    
    const db = locals.db;
    const row = db.prepare('SELECT * FROM calendar WHERE id = ?').get(params.id);
    
    return {
        event: row,
    };
}

export const actions = {
    update: async ({ locals, request, params }) => {
        let db = locals.db;
        
        const formData = await request.formData();
        
        const title = formData.get("title");
        const description = formData.get("description");
        
        if (title === "") {
            return fail(400,{ error: "Title cannot be blank."});
        }
        
        const n = {
            title, description,
        }
        
        const where = { id: params.id, };
        
        let success = dbUpdate(db,"calendar", n, where);
        
        if (!success) {
            return fail(400, { error: "Database error - not saved." });
        }
        
        return {
            success: true,
        }
     }
};