Search code examples
reactjsantdant-design-pro

antd how to get all values of multiple fields with one hook useWatch?


Helllo, I use antd v5. I want to get all values of multiple fields with one hook useWatch.

For example, I need to convert this code:

import {Form, Input} from 'antd';

    const Test = () => {
        const firstName = Form.useWatch('fist_name');
    
        const lastName = Form.useWatch('last_name');
    
        return (
            <Form>
                <Form.Item name="fist_name">
                    <Input />
                </Form.Item>
    
                <Form.Item name="last_name">
                    <Input />
                </Form.Item>
            </Form>
        );
    };

to this code (object firstAndLastNames contains values of all fields 'fist_name' and 'last_name'):

import {Form, Input} from 'antd';

const Test = () => {
    const firstAndLastNames = Form.useWatch(['fist_name', 'last_name']);

    return (
        <Form>
            <Form.Item name="fist_name">
                <Input />
            </Form.Item>

            <Form.Item name="last_name">
                <Input />
            </Form.Item>
        </Form>
    );
};

but I don't understand how to do this, please help


Solution

  • My solution for this issue is to pass empty array in dependences useWatch([], form)