mantinedev / mantine

A fully featured React components library
https://mantine.dev
MIT License
26.79k stars 1.9k forks source link

useForm use uncontrolled mode call form.setValues() in onValuesChange input will lose focus each typed #6859

Closed jackyleefu closed 1 month ago

jackyleefu commented 1 month ago

Dependencies check up

What version of @mantine/* packages do you have in package.json?

7.12.2

What package has an issue?

@mantine/form

What framework do you use?

Vite

In which browsers you can reproduce the issue?

All

Describe the bug

calling form.setValues() in onValuesChange loses the focus of the input box every time you type when using uncontrolled mode, while using controlled mode is fine.

If possible, include a link to a codesandbox with a minimal reproduction

https://codesandbox.io/p/sandbox/8ztwm3?file=%2Fsrc%2FApp.js

Possible fix

No response

Self-service

Kenzo-Wada commented 1 month ago

I don't know the cause right away, so I will investigate a little deeper, but for now, I think using setFieldValue as follows will fix this case

const form = useForm({
    mode: "uncontrolled",
    initialValues: {
      a: "abc",
      b: "",
    },
    onValuesChange: (values, previous) => {
      if (values.a !== previous.a) {
        form.setFieldValue(
          'b', values.a + "xyz",
        );
      }
    },
  });
rtivital commented 1 month ago

This cannot be fixed for uncontrolled form. When form.setValues is called, keys of all inputs are updated and the component is umounted/mounted with a new element in the DOM. In this case, you need to use controlled form mode.