# formActions
Package: @mantine/form
Import: import { FormActions } from '@mantine/form';

## Usage

Form actions allow you to change the form state from anywhere in your application.
The form actions mechanism is similar to the [notifications system](https://mantine.dev/llms/x-notifications.md),
[modals manager](https://mantine.dev/llms/x-modals.md) and other similar packages.

To use form actions, set the `name` property in [use-form](https://mantine.dev/llms/form-use-form.md) settings:

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

export interface DemoFormValues {
  name: string;
  age: number;
}

function Demo() {
  const form = useForm<DemoFormValues>({
    mode: 'uncontrolled',
    name: 'demo-form',
    initialValues: {
      name: '',
      age: 0,
    },
  });
}
```

Then call the `createFormActions` function with the same form name as specified in `useForm` settings:

```tsx
// Import type of form values from the file where you defined useForm
import { createFormActions } from '@mantine/form';
import type { DemoFormValues } from './DemoForm';

export const demoFormActions =
  createFormActions<DemoFormValues>('demo-form');
```

After that, you can use `demoFormActions` to change form state from anywhere in your application.
For example, after a fetch request or after a user interaction with a component that does not have access
to the form state:

```tsx
import { useEffect } from 'react';
import { Button } from '@mantine/core';
import { demoFormActions } from './demoFormActions';

function ExternalComponent() {
  useEffect(() => {
    fetch('/api/user')
      .then((res) => res.json())
      .then((res) =>
        demoFormActions.setValues({
          name: res.name,
          age: res.age,
        })
      );
  }, []);

  return (
    <Button onClick={() => demoFormActions.reset()}>
      Reset demo form
    </Button>
  );
}
```

## Form name

Form names must be strings that contain only letters, numbers and dashes:

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

// ✅ Valid form name
const valid = useForm({
  name: 'valid-FORM-name-10',
  mode: 'uncontrolled',
});

// ❌ Invalid form name: must not contain spaces and special characters
const invalid = useForm({
  name: 'invalid_form name',
  mode: 'uncontrolled',
});
```

Note that form names must be unique. If you have multiple forms with the same name, form actions will
update the state of all forms with that name.

## Form actions

The `createFormActions` function returns an object with the following methods:

* `setFieldValue`
* `setValues`
* `setInitialValues`
* `setErrors`
* `setFieldError`
* `clearFieldError`
* `clearErrors`
* `reset`
* `validate`
* `validateField`
* `reorderListItem`
* `removeListItem`
* `insertListItem`
* `setDirty`
* `setTouched`
* `resetDirty`
* `resetTouched`

All methods work similarly to [use-form](https://mantine.dev/llms/form-use-form.md) hook methods –
the functions accept the same arguments but do not return anything.
