sveltekitsvelte-5sveltekit-superforms

Superforms : updating array of objects


I'm trying to work with schema that looks like this (using zod):

const examSchema = z.object({
    name: z.string().min(4).max(250),
    message: z.string().max(500).optional(),
    maxPoints: z.string(),
    questions: examQuestionSchema.array().min(1),
    shuffleQuestions: z.boolean(),
});

On my svelte frontend i then try to update the questions with a button "add question" that on click does this:

<script lang="ts">
  const { form, errors, constraints, enhance } = superForm<ExamSchema, any, any>(data.form);
</script>

<form enctype="multipart/form-data" method="POST" use:enhance>
    <button
        type="button"
        onclick={() => {
            const newQuestion: ExamSchema['questions'][0] = {
                id: shortUUID.uuid(),
                type: 'abc',
                points: '0',
                question: '',
                answers: [],
            };
            $form.questions = [...$form.questions, newQuestion]
        }}
        class="toolbar-btn"
    >
        <Abc height="16px" width="16px"></Abc>
    </button>
        <button type="submit" class="button-primary save-exam">
            {$i18n.t('teacher_panel.exam_editor.submit')}
        </button>
</form>

Server code:

export const load = async () => {
    const form = await superValidate(zod(examSchema));
    return { form };
};

export const actions = {
    default: async (request) => {
        const form = await superValidate(request, zod(examSchema));
        console.log(form)
        return { form };
    }
} satisfies Actions;

However upon submitting on backend i can log that the data im sending is missing the question despite he UI getting updated properly


Solution

  • changing dataType in the client solved the issue:

    const { form, errors, constraints, enhance } =
        superForm<ExamSchema, any, any>(data.form, {
            dataType: 'json'
        });