Remote functions
Installation
Section titled “Installation”npm i @sjsf/sveltekit@nextyarn add @sjsf/sveltekit@nextpnpm add @sjsf/sveltekit@nextbun add @sjsf/sveltekit@nextExample
Section titled “Example”<script lang="ts"> import { tick } from "svelte"; import { BasicForm, createForm } from "@sjsf/form"; // WARN: You must export this ID Builder in your `defaults` file import { createFormIdBuilder } from "@sjsf/sveltekit/rf"; import { connect } from "@sjsf/sveltekit/rf/client";
import * as defaults from "$lib/form-defaults";
import { createPost, getInitialData } from "./data.remote";
const initialData = await getInitialData();
const form = createForm( await connect( createPost.enhance(async ({ submit }) => { await submit(); if (createPost.fields.allIssues()) { return; } console.log(createPost.result); // Waiting for an update from remote function await tick(); form.reset(); }), { ...defaults, ...initialData, idBuilder: createFormIdBuilder, // Required due to the use of `enhance` fields: createPost.fields, } ) );</script>
<BasicForm {form} novalidate />import type { InitialFormData } from "@sjsf/sveltekit";import { createServerValidator } from "@sjsf/sveltekit/rf/server";
import { form, query } from "$app/server";import * as defaults from "$lib/form-defaults";import { schema, type FormValue } from "$lib/post-model";
export const getInitialData = query(async () => { return { schema, initialValue: { title: "New post", content: "" } satisfies FormValue, } satisfies InitialFormData;});
export const createPost = form( createServerValidator<FormValue>({ ...defaults, schema, }), ({ data: { title, content } }, invalid) => { if (title.length > 100) { invalid({ path: ["title"], message: "Title is too long" }); } return { id: "new-post", title, content }; });import type { FromSchema } from "json-schema-to-ts";import type { Schema } from "@sjsf/form";
export const schema = { title: "Post", type: "object", properties: { title: { title: "Title", type: "string", }, content: { title: "Content", type: "string", minLength: 5, }, }, required: ["title", "content"],} as const satisfies Schema;
export type FormValue = FromSchema<typeof schema>;Known issues
Section titled “Known issues”-
experimental.asyncdoes not apply to dependency code - issue.Add this to your
vite.config.jsoptimizeDeps: {exclude: ['@sjsf/form', '@sjsf/sveltekit/rf/client'],} -
The
form.valuetype on the client side isunknownbecause theRemoteFormtype does not include information about the validator’s output type. For now, you need to specify the type manually:createForm<FormValue>(...).