Skip to content

Commit

Permalink
feat: add array fields move method (#647)
Browse files Browse the repository at this point in the history
  • Loading branch information
t-rosa committed Mar 25, 2024
1 parent cae8bd7 commit 17bf6b5
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 1 deletion.
2 changes: 1 addition & 1 deletion docs/framework/react/guides/basic-concepts.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ Example:

Array fields allow you to manage a list of values within a form, such as a list of hobbies. You can create an array field using the `form.Field` component with the `mode="array"` prop.

When working with array fields, you can use the fields `pushValue`, `removeValue`, and `swapValues` methods to add, remove, and swap values in the array.
When working with array fields, you can use the fields `pushValue`, `removeValue`, `swapValues` and `moveValue` methods to add, remove, and swap values in the array.

Example:

Expand Down
3 changes: 3 additions & 0 deletions packages/form-core/src/FieldApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,9 @@ export class FieldApi<
swapValues = (aIndex: number, bIndex: number) =>
this.form.swapFieldValues(this.name, aIndex, bIndex)

moveValue = (aIndex: number, bIndex: number) =>
this.form.moveFieldValues(this.name, aIndex, bIndex)

validateSync = (value = this.state.value, cause: ValidationCause) => {
const validates = getSyncValidatorArray(cause, this.options)

Expand Down
11 changes: 11 additions & 0 deletions packages/form-core/src/FormApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -718,6 +718,17 @@ export class FormApi<
return setBy(setBy(prev, `${index1}`, prev2), `${index2}`, prev1)
})
}

moveFieldValues = <TField extends DeepKeys<TFormData>>(
field: TField,
index1: number,
index2: number,
) => {
this.setFieldValue(field, (prev: any) => {
prev.splice(index2, 0, prev.splice(index1, 1)[0])
return prev
})
}
}

function normalizeError(rawError?: ValidationError) {
Expand Down
17 changes: 17 additions & 0 deletions packages/form-core/src/tests/FieldApi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,23 @@ describe('field api', () => {
expect(field.getValue()).toStrictEqual(['two', 'one'])
})

it('should move a value from an array value correctly', () => {
const form = new FormApi({
defaultValues: {
names: ['one', 'two', 'three', 'four'],
},
})

const field = new FieldApi({
form,
name: 'names',
})

field.moveValue(2, 0)

expect(field.getValue()).toStrictEqual(['three', 'one', 'two', 'four'])
})

it('should not throw errors when no meta info is stored on a field and a form re-renders', async () => {
const form = new FormApi({
defaultValues: {
Expand Down

0 comments on commit 17bf6b5

Please sign in to comment.