Form values

Set initial values, load data, update and reset values

Initial values

In most cases you should set initialValues. They define the fields of the form and their types, and they are used by form.reset and dirty checks:

import { useForm } from '@mantine/form';

const form = useForm({
  initialValues: {
    name: '',
    email: '',
  },
});

To change values after the form was created, use one of the handlers below:

  • form.initialize – load a record once, sets both values and initial values
  • form.setValues and form.setFieldValue – update values, initial values stay the same
  • form.setInitialValues – change the values used by form.reset and dirty checks
  • form.reset and form.resetField – go back to initial values

getValues

form.getValues() returns the current values. Use it in event handlers and callbacks. form.values is a snapshot from the last render, it is outdated in handlers and is not updated while the user types in uncontrolled mode:

import { useForm } from '@mantine/form';

const form = useForm({
  initialValues: { name: 'John Doe' },
});

form.getValues(); // { name: 'John Doe' }

form.setValues({ name: 'John Smith' });
form.getValues(); // { name: 'John Smith' }

To render a value or run an effect when it changes, see Watching values.

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 '@mantine/form';
import { TextInput, Button, Group } from '@mantine/core';
import { randomId } from '@mantine/hooks';

function Demo() {
  const form = useForm({
    initialValues: {
      name: '',
      email: '',
    },
  });

  return (
    <div>
      <TextInput
        label="Name"
        placeholder="Name"
        {...form.getInputProps('name')}
      />
      <TextInput
        mt="md"
        label="Email"
        placeholder="Email"
        {...form.getInputProps('email')}
      />

      <Group justify="center" mt="xl">
        <Button
          onClick={() =>
            form.setValues({
              name: randomId(),
              email: `${randomId()}@test.com`,
            })
          }
        >
          Set random values
        </Button>
      </Group>
    </div>
  );
}

setValues partial

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

import { useForm } from '@mantine/form';

const form = useForm({
  initialValues: { name: '', email: '', age: 0 },
});

form.setValues({ name: 'John', age: 21 });
form.getValues(); // -> { name: 'John', email: '', age: 21 }

setFieldValue handler

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

import { useForm } from '@mantine/form';
import { TextInput, Button, Group } from '@mantine/core';
import { randomId } from '@mantine/hooks';

function Demo() {
  const form = useForm({
    initialValues: {
      name: '',
      email: '',
    },
  });

  return (
    <div>
      <TextInput
        label="Name"
        placeholder="Name"
        {...form.getInputProps('name')}
      />
      <TextInput
        mt="md"
        label="Email"
        placeholder="Email"
        {...form.getInputProps('email')}
      />

      <Group justify="center" mt="xl">
        <Button onClick={() => form.setFieldValue('name', randomId())}>Random name</Button>
        <Button onClick={() => form.setFieldValue('email', `${randomId()}@test.com`)}>
          Random email
        </Button>
      </Group>
    </div>
  );
}

setFieldValue without form rerender

In uncontrolled mode, form.setFieldValue rerenders the form component so that any input receives the new value. Pass { forceUpdate: false } to skip that render: the input subscribed to the field updates alone, the same way as when the user types. Use it when a field is set on every change of another field, for example to generate a URL slug from a name:

import { TextInput } from '@mantine/core';
import { useForm } from '@mantine/form';

function slugify(value: string) {
  return value
    .toLowerCase()
    .replace(/\s+/g, '-')
    .replace(/[^a-z0-9-]/g, '');
}

function Demo() {
  const form = useForm({
    touchTrigger: 'focus',
    initialValues: { name: '', slug: '' },
  });

  form.watch('name', ({ value }) => {
    // Stop generating the slug once the user has edited it
    if (!form.isTouched('slug')) {
      form.setFieldValue('slug', slugify(value), { forceUpdate: false });
    }
  });

  return (
    <>
      <TextInput label="Name" {...form.getInputProps('name')} />
      <TextInput label="Slug" {...form.getInputProps('slug')} />
    </>
  );
}

If the input of the field is not subscribed, for example a native input element, the form component rerenders anyway to pass the new value. The option has no effect in controlled mode.

Initialize form

form.initialize sets initialValues and values to the same value and marks the form as initialized. Only the first call changes values: later calls keep values and initial values as they are and only clear errors. form.initialized is true after the first call.

form.initialize is useful when you want to sync form values with backend API response:

import { Button, NumberInput, TextInput } from '@mantine/core';
import { isInRange, isNotEmpty, useForm } from '@mantine/form';

interface FormValues {
  name: string;
  age: number | string;
}

function apiRequest(): Promise<FormValues> {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ name: 'John Doe', age: 25 });
    }, 1000);
  });
}

function Demo() {
  const form = useForm<FormValues>({
    initialValues: { name: '', age: 0 },
    validate: {
      name: isNotEmpty('Name is required'),
      age: isInRange({ min: 18 }, 'You must be at least 18 to register'),
    },
  });

  return (
    <>
      <TextInput
        {...form.getInputProps('name')}
        label="Name"
        placeholder="Name"
      />
      <NumberInput
        {...form.getInputProps('age')}
        label="Age"
        placeholder="Age"
        mt="md"
      />
      <Button onClick={() => apiRequest().then((values) => form.initialize(values))} mt="md">
        Initialize form
      </Button>
    </>
  );
}

Example with TanStack Query (react-query):

import { useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useForm } from '@mantine/form';

function Demo() {
  const query = useQuery({
    queryKey: ['current-user'],
    queryFn: () => fetch('/api/users/me').then((res) => res.json()),
  });

  const form = useForm({
    initialValues: {
      name: '',
      email: '',
    },
  });

  useEffect(() => {
    if (query.data) {
      // Even if query.data changes, the form will be initialized only once
      form.initialize(query.data);
    }
  }, [query.data]);
}

Note that form.initialize will erase all values that were set before it was called. It is usually a good idea to set readOnly or disabled on all form fields before form.initialize is called to prevent data loss. You can implement this with enhanceGetInputProps:

import { NumberInput, TextInput, Button } from '@mantine/core';
import { useForm } from '@mantine/form';

interface FormValues {
  name: string;
  age: number | string;
}

function Demo() {
  const form = useForm<FormValues>({
    initialValues: { name: '', age: '' },
    enhanceGetInputProps: (payload) => {
      if (!payload.form.initialized) {
        return { disabled: true };
      }

      return {};
    },
  });

  return (
    <>
      <TextInput
        {...form.getInputProps('name')}
        label="Your name"
        placeholder="Your name"
      />
      <NumberInput
        {...form.getInputProps('age')}
        label="Age"
        placeholder="Age"
        mt="md"
      />
      <Button onClick={() => form.initialize({ name: 'John', age: 20 })} mt="md">
        Initialize form
      </Button>
    </>
  );
}

reset handler

The form.reset handler sets values to initialValues, clears all errors and resets touched and dirty state. With a type="reset" button, use form.onReset as the onReset handler of the form element instead:

import { useForm } from '@mantine/form';
import { TextInput, Button, Group } from '@mantine/core';

function Demo() {
  const form = useForm({
    initialValues: {
      name: '',
      email: '',
    },
  });

  return (
    <div>
      <TextInput
        label="Name"
        placeholder="Name"
        {...form.getInputProps('name')}
      />
      <TextInput
        mt="md"
        label="Email"
        placeholder="Email"
        {...form.getInputProps('email')}
      />

      <Group justify="center" mt="xl">
        <Button onClick={() => form.reset()}>Reset to initial values</Button>
      </Group>
    </div>
  );
}

resetField handler

The form.resetField handler sets the value of a single field to its initial value and clears its error and dirty state:

import { useForm } from '@mantine/form';

const form = useForm({
  initialValues: { name: 'John', email: 'john@mantine.dev' },
});

form.setValues({ name: 'Jane', email: 'jane@mantine.dev' });
form.resetField('name');
form.getValues(); // -> { name: 'John', email: 'jane@mantine.dev' }

setInitialValues handler

The form.setInitialValues handler allows you to update initialValues after the form was initialized. form.getInitialValues() returns the current initial values:

import { useEffect } from 'react';
import { useForm } from '@mantine/form';

function Demo() {
  const form = useForm({
    initialValues: {
      name: '',
      email: '',
    },
  });

  useEffect(() => {
    fetch('/api/user')
      .then((res) => res.json())
      .then((data) => {
        // Update initial values after the form was initialized
        // These values will be used in form.reset
        // and to compare values to get the dirty state
        form.setInitialValues(data);
        form.setValues(data);
      });
  }, []);
}

Values and object identity

Form values are not cloned: objects passed to initialValues, form.setValues, form.setFieldValue and form.initialize are stored as is. Do not mutate them after they were passed to the form.