---
# System prepended metadata

title: Accessing form data
tags: [zeta-dom-react]

---

---
tags: zeta-dom-react
---

# Accessing form data

Field data is accessible by `form.data` property.

When using TypeScript, it can be benefited by specifying type argument for data shape:

```typescript
interface LoginData {
    username: string;
    password: string;
}

function Login() {
    const form = useFormContext<LoginData>();
    const onClick = () => {
        // access field values through `form.data`
        login(
            form.data.username,
            form.data.password);
    };

    return (
        <Form context={form}>
            <TextField name="username" required={true} label="Username" />
            <TextField name="password" required={true} type="password" label="Password" />
            <Button label="Login" onClick={onClick} />
        </Form>
    );
}
```

## Effects on field update

Every time field value is updated, either programmatically or by user actions, re-rendering is triggered.

In the following example, the paragraph will always show the entered text:

```typescript
function Component() {
    const form = useFormContext();
    return (
        <Form context={form}>
            {/* print current value */}
            <p>Value is {form.data.item || ''}</p>
            <TextField name="item" />
        </Form>
    );
}
```

The standard `useEffect` hook will work on form data:


```typescript
function Component() {
    const form = useFormContext();

    useEffect(() => {
        // do stuff when text field updates
    }, [form.data.item]);

    return (
        <Form context={form}>
            <TextField name="item" />
        </Form>
    );
}
```

The `FormContext` object also provides `dataChange` event if you needs logic depending on which fields were updated:

```typescript
function Component() {
    const form = useFormContext();

    useEffect(() => {
        return form.on('dataChange', e => {
            // print out which fields were changed
            console.log(e.data);
        });
    }, []);

    return (
        <Form context={form}>
            <TextField name="item1" />
            <TextField name="item2" />
            <TextField name="item3" />
        </Form>
    );
}
```

## Updating field

Field values can be updated on `form.data` and they will be reflected on the rendered control:

```typescript
function Component() {
    const form = useFormContext();
    return (
        <Form context={form}>
            <TextField name="item" />
            {/* clicking the button will fill text field with "foo" */}
            <button onClick={() => form.data.item = 'foo'} />
        </Form>
    );
}
```


