Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useFieldArray remove method support array of indexes #980

Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/useFieldArray.test.ts
Expand Up @@ -345,6 +345,35 @@ describe('useFieldArray', () => {
expect(result.current.fields).toEqual([]);
});

it('should remove specific fields when index is array', () => {
const { result } = renderHook(() =>
useFieldArray({
control: reconfigureControl({
defaultValuesRef: {
current: { test: [{ test: '1' }, { test: '2' }, { test: '3' }] },
},
getValues: () => ({
test: [],
}),
fieldsRef: {
current: {
'test[0]': { ref: { name: 'test[0]', value: { test: '1' } } },
'test[1]': { ref: { name: 'test[1]', value: { test: '2' } } },
'test[2]': { ref: { name: 'test[2]', value: { test: '3' } } },
},
},
}),
name: 'test',
}),
);

act(() => {
result.current.remove([0, 2]);
});

expect(result.current.fields).toEqual([{ test: '2', id: '1' }]);
});

it('should insert data at index', () => {
const { result } = renderHook(() =>
useFieldArray({
Expand Down
2 changes: 1 addition & 1 deletion src/useFieldArray.ts
Expand Up @@ -119,7 +119,7 @@ export function useFieldArray<
}
};

const remove = (index?: number) => {
const remove = (index?: number | number[]) => {
if (!isUndefined(index)) {
mapCurrentFieldsValueWithState();
}
Expand Down
6 changes: 4 additions & 2 deletions src/utils/remove.ts
@@ -1,7 +1,9 @@
import isArray from './isArray';
import isUndefined from './isUndefined';

export default (data: any, index?: number) =>
export default (data: any, index?: number | number[]) =>
!isUndefined(index) && isArray(data)
? [...data.slice(0, index), ...data.slice(index + 1)]
? isArray(index)
? data.filter((_e, i) => index.indexOf(i) === -1)
: [...data.slice(0, index), ...data.slice(index + 1)]
: [];