Skip to content

Commit

Permalink
💅 close #7023 issue with async useFieldArray actions (#7029)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluebill1049 authored Nov 11, 2021
1 parent 3ec6f05 commit e0fb6de
Show file tree
Hide file tree
Showing 18 changed files with 133 additions and 4,745 deletions.
78 changes: 77 additions & 1 deletion src/__tests__/useFieldArray.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { useFieldArray } from '../useFieldArray';
import { useForm } from '../useForm';
import { FormProvider } from '../useFormContext';

export const mockGenerateId = () => {
const mockGenerateId = () => {
let id = 0;
jest.spyOn(generateId, 'default').mockImplementation(() => (id++).toString());
};
Expand Down Expand Up @@ -2610,4 +2610,80 @@ describe('useFieldArray', () => {
).toEqual('1sub-new');
});
});

it('should update field array correctly with async invocation', async () => {
type FormValues = {
items: { id: string; name: string }[];
};

let controlObj: any = {};

const App = () => {
const { register, control, getValues } = useForm<FormValues>({
mode: 'onChange',
defaultValues: {
items: [{ name: 'one' }, { name: 'two' }],
},
});

controlObj = control;

const { fields, remove, insert } = useFieldArray({
control,
name: 'items',
});

return (
<form>
{fields.map((field, index) => {
return (
<div key={field.id}>
<button
type="button"
onClick={() => {
setTimeout(() => {
remove(index);
});
}}
>
remove
</button>
<button
type="button"
onClick={() => {
setTimeout(() => {
const { id, ...rest } = getValues(`items.${index}`);
insert(index + 1, {
...rest,
name: 'test',
});
});
}}
>
copy
</button>
<input
{...register(`items.${index}.name` as const, {
required: true,
})}
/>
</div>
);
})}
</form>
);
};

render(<App />);

await actComponent(async () => {
fireEvent.click(screen.getAllByRole('button', { name: 'copy' })[0]);
});

await actComponent(async () => {
fireEvent.click(screen.getAllByRole('button', { name: 'remove' })[0]);
});

expect(controlObj._fields.items.length).toEqual(2);
});
});
Loading

0 comments on commit e0fb6de

Please sign in to comment.