Skip to content

Provide a way to update form fields values inside the form itself  #23

Description

@abdulhadi-lababidi98

As I mentioned in this issue I had a use case where I needed to update a field value inside the form element, And clearly the useField is not the solution.

I tried to set the data of the form like this

export const ProductDefinitionMigrateForm: React.FC = () => {
    const { buttonRef, onSubmitFailed } = useFormErrorHandling();
    const [data, setData] = useState(() => Morfi.initialData(_formInitialData()));
    const { Form, fields } = Morfi.useForm<ProductDefinitionMigrateFormData>();
    DirtyGuard.useForm(data);

    const cb = useCallback((newVal: string) => {
        setData({
            ...data,
            values: {
                ...data.values,
                productVersion: newVal
            }
        });
    }, []);

And the value did not update, also this introduced very weird behaviours.

So I had to create a child component and pass everything to it to solve this problem.

Expected Behaviour

To have an easy way to update field values inside form element

Suggested Solution

Make the useForm hook provides a function to update fields values

export const ProductDefinitionMigrateForm: React.FC = () => {
    const { buttonRef, onSubmitFailed } = useFormErrorHandling();
    const [data, setData] = useState(() => Morfi.initialData(_formInitialData()));
    const { Form, fields, updateValues } = Morfi.useForm<ProductDefinitionMigrateFormData>();
    DirtyGuard.useForm(data);

    const updateProductVersion = useCallback((newVal: string) => {
        updateValues('productVersion', newVal);
    }, []);

One other suggestion, if setting the data here (as I did in the first code snippet) will break something in the form. We should not allow that, maybe we can add new hook that is safer, something like this:

    const {Form, fields, data, updateValues } = Morfi.useForm_V2(_formInitialData());

inside this hook version we will create the form state internally and pass it to the Form before returning it, So the returned Form element will not need the data and onChange props

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions