v6.0.35

Form values

Manipulate form values with use-form

Initial values

In most cases you should set initialValues:

import { useForm } from '@asuikit/form';
const form = useForm({
initialValues: {
name: '',
email: '',
},
});

setValues handler

With form.setValues you can set all form values, for example you can set values after you have received a response from the backend API:

import { useForm } from '@asuikit/form';
import { TextInput, Button, Group, Box } from '@asuikit/core';
import { randomId } from '@asuikit/hooks';
function Demo() {
const form = useForm({
initialValues: {
name: '',
email: '',
},
});
return (
<Box maw={320} mx="auto">
<TextInput label="Name" placeholder="Name" {...form.getInputProps('name')} />
<TextInput mt="md" label="Email" placeholder="Email" {...form.getInputProps('email')} />
<Group position="center" mt="xl">
<Button
variant="outline"
onClick={() =>
form.setValues({
name: randomId(),
email: `${randomId()}@test.com`,
})
}
>
Set random values
</Button>
</Group>
</Box>
);
}

setValues partial

form.setValues can also be used to set multiple values at once, payload will be shallow merged with current values state:

import { useForm } from '@asuikit/form';
const form = useForm({ initialValues: { name: '', email: '', age: 0 } });
form.setValues({ name: 'John', age: 21 });
form.values; // -> { name: 'John', email: '', age: 21 }

setFieldValue handler

form.setFieldValue handler allows to set value of the field at given path:

import { useForm } from '@asuikit/form';
import { TextInput, Button, Group, Box } from '@asuikit/core';
import { randomId } from '@asuikit/hooks';
function Demo() {
const form = useForm({
initialValues: {
name: '',
email: '',
},
});
return (
<Box maw={320} mx="auto">
<TextInput label="Name" placeholder="Name" {...form.getInputProps('name')} />
<TextInput mt="md" label="Email" placeholder="Email" {...form.getInputProps('email')} />
<Group position="center" mt="xl">
<Button variant="outline" onClick={() => form.setFieldValue('name', randomId())}>
Random name
</Button>
<Button
variant="outline"
onClick={() => form.setFieldValue('email', `${randomId()}@test.com`)}
>
Random email
</Button>
</Group>
</Box>
);
}

reset handler

form.reset handler sets values to initialValues and clear all errors:

import { useForm } from '@asuikit/form';
import { TextInput, Button, Group, Box } from '@asuikit/core';
function Demo() {
const form = useForm({
initialValues: {
name: '',
email: '',
},
});
return (
<Box maw={320} mx="auto">
<TextInput label="Name" placeholder="Name" {...form.getInputProps('name')} />
<TextInput mt="md" label="Email" placeholder="Email" {...form.getInputProps('email')} />
<Group position="center" mt="xl">
<Button variant="outline" onClick={() => form.reset()}>
Reset to initial values
</Button>
</Group>
</Box>
);
}

transformValues

Use transformValues to transform values before they get submitted in onSubmit handler. For example, it can be used to merge several fields into one or to convert types:

import { useState } from 'react';
import { useForm } from '@asuikit/form';
import { TextInput, Button, Box, Code } from '@asuikit/core';
function Demo() {
const [submittedValues, setSubmittedValues] = useState('');
const form = useForm({
initialValues: {
firstName: 'Jane',
lastName: 'Doe',
age: '33',
},
transformValues: (values) => ({
fullName: `${values.firstName} ${values.lastName}`,
age: Number(values.age) || 0,
}),
});
return (
<Box maw={400} mx="auto">
<form
onSubmit={form.onSubmit((values) => setSubmittedValues(JSON.stringify(values, null, 2)))}
>
<TextInput
label="First name"
placeholder="First name"
{...form.getInputProps('firstName')}
/>
<TextInput
label="Last name"
placeholder="Last name"
mt="md"
{...form.getInputProps('lastName')}
/>
<TextInput
type="number"
label="Age"
placeholder="Age"
mt="md"
{...form.getInputProps('age')}
/>
<Button type="submit" mt="md">
Submit
</Button>
</form>
{submittedValues && <Code block>{submittedValues}</Code>}
</Box>
);
}

Get transformed values

You can get transformed values outside of form.onSubmit method by calling form.getTransformedValues. It accepts values that need to be transformed as optional argument, if it is not provided, then the result of form.values transformation will be returned instead:

import { useForm } from '@asuikit/form';
function Demo() {
const form = useForm({
initialValues: {
firstName: 'John',
lastName: 'Doe',
},
transformValues: (values) => ({
fullName: `${values.firstName} ${values.lastName}`,
}),
});
form.getTransformedValues(); // -> { fullName: 'John Doe' }
form.getTransformedValues({
firstName: 'Jane',
lastName: 'Loe',
}); // { fullName: 'Jane Loe' }
}

Get values type

import { useForm } from '@asuikit/form';
function Demo() {
const form = useForm({ initialValues: { name: '', age: 0 } });
// Get inferred form values type, will be `{ name: string; age: number }`
type FormValues = typeof form.values;
// Use values type in handleSubmit function or anywhere else
const handleSubmit = (values: FormValues) => console.log(values);
}

Get transformed values type

To get transformed values (output of transformValues) use TransformedValues type. It is useful when you want to create a custom submit function:

import { useForm, TransformedValues } from '@asuikit/form';
function Demo() {
const form = useForm({
initialValues: {
name: '',
locationId: '2',
},
transformValues: (values) => ({
...values,
locationId: Number(values.locationId),
}),
});
type Transformed = TransformedValues<typeof form>;
// -> { name: string, locationId: number }
const handleSubmit = (values: TransformedValues<typeof form>) => {};
return <form onSubmit={form.onSubmit(handleSubmit)} />;
}

Set values type

By default, form values types will be inferred from initialValues. To avoid that, you can pass type to useForm hook, this approach is useful when types cannot be correctly inferred or when you want to provide more specific types:

import { useForm } from '@asuikit/form';
interface FormValues {
name: string; // regular field, same as inferred type
role: 'user' | 'admin'; // union, more specific than inferred string type
// values that may be undefined or null
// cannot be correctly inferred in strict mode
age: number | undefined;
registeredAt: Date | null;
// Arrays that are empty cannot be inferred correctly
jobs: string[];
}
function Demo() {
const form = useForm<FormValues>({
initialValues: {
name: '',
role: 'user',
age: undefined,
registeredAt: null,
jobs: [],
},
});
}