form.resetDirty() expected behavior?
See original GitHub issueWhat package has an issue
Describe the bug
Before diving into the code, I just wanted to ask if this is expected behavior. It doesn’t seem like it is, but maybe I’m using the API incorrectly.
Here’s the setup. We have a form with a single field, which initially has a value of “a”. Since it’s not dirty, the “Save” button is disabled. The user changed the input value to “b”. The form is now dirty so the button is enabled.
The user clicks “Save”, some network stuff happens (aka, the db is synced with the form data) and then we call form.resetDirty()
. Everything is synced, the form data is clean and the button is disabled again.
Awesome. So far…
Now change the value back to “a”. Uh oh. The form isn’t dirty and the user can’t save. The user can now change the value to “b” and it’s still dirty. The user can set the value to anything other than the initial value and it’s still dirty.
Now it seems we have a mess on our hands.
import { TextInput, Text, Button, MantineProvider } from "@mantine/core";
import { useForm } from "@mantine/form";
export default function App() {
const form = useForm({ initialValues: { text: "a" } });
const handleSubmit = () => {
// mutateSomeData(form.values);
form.resetDirty();
};
return (
<MantineProvider withGlobalStyles withNormalizeCSS>
<form onSubmit={form.onSubmit(handleSubmit)}>
<TextInput {...form.getInputProps("text")} label="Touched/dirty demo" />
<Button type="submit" mt="lg" disabled={!form.isDirty()}>
Save
</Button>
</form>
<Text size="sm" mt="sm">
Touched:{" "}
<Text span color={form.isTouched("text") ? "blue" : "red"}>
{form.isTouched("text") ? "touched" : "not touched"}
</Text>
</Text>
<Text size="sm">
Dirty:{" "}
<Text span color={form.isDirty("text") ? "blue" : "red"}>
{form.isDirty("text") ? "dirty" : "not dirty"}
</Text>
</Text>
</MantineProvider>
);
}
What version of @mantine/hooks page do you have in package.json?
5.1.3
If possible, please include a link to a codesandbox with the reproduced problem
https://codesandbox.io/s/dreamy-satoshi-sfkijt?file=/src/App.tsx
Do you know how to fix the issue
No
Are you willing to participate in fixing this issue and create a pull request with the fix
Yes
Possible fix
I haven’t looked at the source, but it seems like isDirty()
is just comparing the initial state with the current state, whereas if resetDirty()
is invoked, isDirty()
should compare the state when resetDirty()
was last invoked.
Issue Analytics
- State:
- Created a year ago
- Comments:6 (6 by maintainers)
Top GitHub Comments
Hi @bbar, currently
form.resetDirty()
compares values withinitialValues
, but I think we can change the logic to make it work as you’ve proposed. I’ll change it in the next minor release.Released in 5.2.0