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

Sveltekit form actions with super forms clearing input before post

$
0
0

I have a register form that takes an email and password. It is validated using zod and SuperForms. When I submit the form the data from the form is cleared before requesting the form action defined in +page.server.ts.

How do I fix this to pass the form data to +page.server.ts properly?

When clicking submit a request can be seen in the network calls and when logged in the +page.server.ts gives response

Request (0 KB) {  method: "POST",  url: "http://localhost:5173/register?/register",  headers: Headers {"host": "localhost:5173","connection": "keep-alive","content-length": "152","accept": "application/json","content-type": "multipart/form-data; boundary=----WebKitFormBoundaryDpiWF58YTcB17kNP","user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36","origin": "http://localhost:5173","sec-fetch-mode": "cors","sec-fetch-dest": "empty","referer": "http://localhost:5173/register?/register","accept-encoding": "gzip, deflate, br, zstd","accept-language": "en-GB,en-US;q=0.9,en;q=0.8","sec-ch-ua": "\"Not A(Brand\";v=\"99\", \"Google Chrome\";v=\"121\", \"Chromium\";v=\"121\"","x-sveltekit-action": "true","sec-ch-ua-mobile": "?0","sec-ch-ua-platform": "\"Windows\"","sec-fetch-site": "same-origin",  }  ReadableStream {    locked: [Getter],    cancel: [Function: cancel],    getReader: [Function: getReader],    pipeTo: [Function: pipeTo],    pipeThrough: [Function: pipeThrough],    tee: [Function: tee],    values: [Function: values],    [Symbol(Symbol.asyncIterator)]: [Function: lazyAsyncIterator],  }}{  id: "1p3ituu",  valid: false,  posted: true,  errors: {    email: [ "Please enter a valid email address" ],    password: [ "Password must be at least 8 characters long" ],  },  data: {    email: "",    password: "",  },}

this shows that the email and password aren't being passed to the server.

I know that the data is entering the form properly as the values can be seen here in the superforms debug view

enter image description here

Code

register-form.svelte

<script lang="ts">    import { Label } from "$lib/components/ui/label";    import { Input } from "$lib/components/ui/input";    import { Button } from "$lib/components/ui/button";    import SuperDebug from "sveltekit-superforms";    import {        registerFormSchema,        type RegisterFormSchema,    } from "./register-form";    import {        type SuperValidated,        type Infer,        superForm,    } from "sveltekit-superforms";    import { zodClient } from "sveltekit-superforms/adapters";    export let data: { form: SuperValidated<RegisterFormSchema> };    const form = superForm(data.form, {        validators: zodClient(registerFormSchema),        multipleSubmits: "prevent",    });    const { form: formData, errors, enhance } = form;</script><form method="POST" use:enhance><div class="form-sections flex gap-4 flex-col"><div class="form-input flex flex-col gap-2"><Label for="email">Email</Label><Input type="email" bind:value={$formData.email} />            {#if $errors.email}<span class="invalid text-red-600">{$errors.email}</span>{/if}</div><div class="form-input flex flex-col gap-2"><Label for="password">Password</Label><Input type="password" bind:value={$formData.password} />            {#if $errors.password}<span class="invalid text-red-600">{$errors.password}</span>{/if}</div><Button on:click|once type="submit" class="w-full">Create account</Button></div></form><SuperDebug data={formData} />

+page.server.ts

import type { PageServerLoad, Actions } from './$types';import { fail } from '@sveltejs/kit';import { superValidate } from 'sveltekit-superforms';import { zod } from 'sveltekit-superforms/adapters';import { registerFormSchema } from './register-form';import { unauthenticatedRequest } from '@/services/api-service/apiService';export const load: PageServerLoad = async () => {    return {        form: await superValidate(zod(registerFormSchema))    };}export const actions: Actions = {    register: async ({ request }) => {        console.log("register action called")        // console.log(request);        const form = await superValidate(request, zod(registerFormSchema));        console.log(form);        if (!form.valid) {            console.log("form not valid")            return fail(400, {                form,            });        }        const { email, password } = form.data;        console.log(email, password);        const response = await unauthenticatedRequest('POST', 'auth/register', {            email,            password,        });        console.log(response);        switch (response.status) {            case 201:                return {                    status: 201,                    headers: {'set-cookie': response.headers.get('set-cookie'),                    },                    form                };            case 409:                return {                    status: 409,                    body: {                        error: 'User already exists',                    },                    form                };        }        return {            form,        };    },};

+page.svelte

// page definition imports Register form and uses it in a card// ...</div></div><RegisterForm {data} /></Card.Content></Card.Root>

Viewing all articles
Browse latest Browse all 1541

Trending Articles



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