Skip to content

Commit

Permalink
[@mantine/form] Improve key logic in getInputProps
Browse files Browse the repository at this point in the history
  • Loading branch information
rtivital committed Apr 6, 2024
1 parent 06cb7d3 commit 3c55e3e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
19 changes: 9 additions & 10 deletions packages/@mantine/form/src/stories/Form.usage.story.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable no-console */
import React from 'react';
import { Button, Checkbox, Group, NativeSelect, Textarea, TextInput } from '@mantine/core';
import { Button, Checkbox, Group, NativeSelect, Select, Textarea, TextInput } from '@mantine/core';
import { useForm } from '../use-form';
import { FormBase } from './_base';

Expand Down Expand Up @@ -88,27 +88,26 @@ export function ControlMode() {
},
});

// const [key, setKey] = useState('initial');

console.log('render');

return (
<FormBase form={form}>
<Select
label="select"
defaultDropdownOpened
data={['React', 'Angular']}
{...form.getInputProps('select')}
/>

<TextInput label="Name" {...form.getInputProps('name')} />
<Checkbox
mt="md"
label="Accept terms of use"
{...form.getInputProps('terms', { type: 'checkbox' })}
/>
<Textarea label="area" {...form.getInputProps('area')} />
<NativeSelect
label="native select"
data={['React', 'Angular']}
{...form.getInputProps('select')}
/>

<Group mt="xl">
<Button onClick={() => console.log(form.getValues())}>Get form values</Button>
<Button onClick={() => form.setFieldValue('name', 'test-name')}>Set name</Button>
<Button
onClick={() =>
form.setValues({ name: 'updated', terms: true, area: 'updated', select: 'React' })
Expand Down
9 changes: 7 additions & 2 deletions packages/@mantine/form/src/use-form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export function useForm<
const $status = useFormStatus<Values>({ initialDirty, initialTouched, $values, mode });
const $list = useFormList<Values>({ $values, $errors, $status });
const [formKey, setFormKey] = useState(0);
const [fieldKeys, setFieldKeys] = useState<Record<string, number>>({});

const reset: Reset = useCallback(() => {
$values.resetValues();
Expand Down Expand Up @@ -83,7 +84,11 @@ export function useForm<
}
: null,
options?.forceUpdate !== false && mode !== 'controlled'
? () => setFormKey((key) => key + 1)
? () =>
setFieldKeys((keys) => ({
...keys,
[path as string]: (keys[path as string] || 0) + 1,
}))
: null,
],
});
Expand Down Expand Up @@ -126,7 +131,7 @@ export function useForm<
const payload: any = { onChange };

if (mode === 'uncontrolled') {
payload.key = `${formKey}-${path as string}`;
payload.key = `${formKey}-${path as string}-${fieldKeys[path as string] || 0}`;
}

if (withError) {
Expand Down

0 comments on commit 3c55e3e

Please sign in to comment.