Skip to content

useForm

Overview

Generate and provide a form context for a form, using the provided initial values, including methods to update the form's values, errors, messages, touched state, modified state, and to reset the form.

Signature

useForm(props)

Parameters

NameTypeRequiredDescription
propsobjectyesThe form context's initial values.

props Properties

NameTypeRequiredDefaultDescription
initialValuesobjectThe form's initial values. Not mutated, but changes reset the form.

Returns

FormContext

Examples

vue
<script setup>
import Button from "@vueda/controls/button/Button.vue"
import { ConfirmationRequiredError, ServerFeedbackError } from "@vueda/utils/errors.js";
const myState = reactive({
    submitting: false,
    // when initialValues is changed, the form's values are reset to match
    initialValues: {},
});
const formContext = useForm(myState);
const handleSubmit = async () => {
    try {
        myState.submitting = true;
        // allow all validation to run
        formContext.setAllTouched();
        await nextTick();
        if (formContext.state.anyError) {
            return;
        }
        if (!formContext.state.anyModified) {
            return;
        }
        await submitToServer(formContext.state.submittingValues);
    } catch (e) {
        if (e instanceof ServerFeedbackError && !(e instanceof ConfirmationRequiredError)) {
            formContext.handleServerFormValidationError(e);
            return;
        }
        throw e;
    } finally {
        myState.submitting = false;
    }
};
</script>
<template>
<form @submit.prevent="handleSubmit">
    <form-message type="error" />
    <form-message type="message" />
    <form-field name="field1" label="Field 1">
        <form-label>
            <widget-input />
        </form-label>
    </form-field>
    <form-field name="field2" label="Field 2" validation="numeric" :max-value="100" :min-value="1">
        <form-label>
            <widget-input step="1" />
        </form-label>
    </form-field>
    <Button type="submit">Submit</Button>
</form>
</template>

Source

client/lib/use/useForm.js:660

Documents matching: server v3.0.0a1.post1client v3.0.0-alpha.2