Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions src/FieldArray.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -722,6 +722,54 @@ describe('FieldArray', () => {
expect(queryByTestId('child')).not.toBe(null)
})

it('should aggregate subscribed active and touched meta from array fields', () => {
const { getByTestId } = render(
<Form
onSubmit={onSubmitMock}
mutators={arrayMutators as any}
subscription={{}}
initialValues={{ names: ['Paul', 'George'] }}
>
{() => (
<form>
<FieldArray name="names" subscription={{ active: true, touched: true }}>
{({ fields, meta }) => (
<div>
<div data-testid="arrayActive">
{meta.active ? 'Active' : 'Inactive'}
</div>
<div data-testid="arrayTouched">
{meta.touched ? 'Touched' : 'Untouched'}
</div>
{fields.map((field) => (
<Field name={field} key={field}>
{({ input }) => (
<input {...input} data-testid={`${field}.input`} />
)}
</Field>
))}
</div>
)}
</FieldArray>
</form>
)}
</Form>
)

expect(getByTestId('arrayActive')).toHaveTextContent('Inactive')
expect(getByTestId('arrayTouched')).toHaveTextContent('Untouched')

fireEvent.focus(getByTestId('names[0].input'))

expect(getByTestId('arrayActive')).toHaveTextContent('Active')
expect(getByTestId('arrayTouched')).toHaveTextContent('Untouched')

fireEvent.blur(getByTestId('names[0].input'))

expect(getByTestId('arrayActive')).toHaveTextContent('Inactive')
expect(getByTestId('arrayTouched')).toHaveTextContent('Touched')
})

it('should provide default isEqual that does shallow compare of items', () => {
const { getByTestId } = render(
<Form
Expand Down
49 changes: 45 additions & 4 deletions src/useFieldArray.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useMemo } from 'react';
import { useForm, useField } from 'react-final-form'
import { fieldSubscriptionItems, ARRAY_ERROR } from 'final-form'
import { useForm, useField, useFormState } from 'react-final-form'
import { ARRAY_ERROR } from 'final-form'
import { Mutators } from 'final-form-arrays'
import { FieldValidator, FieldSubscription } from 'final-form'
import { FieldArrayRenderProps, UseFieldArrayConfig } from './types'
Expand All @@ -11,9 +11,12 @@ import copyPropertyDescriptors from './copyPropertyDescriptors'
// Default subscription for FieldArray: `length`, `value`, and `error` are included
// so that array-level validation errors are surfaced without subscribing to everything.
// The old default (`all`) caused severe performance degradation with nested arrays (#119).
// Users who need additional meta (e.g. touched, dirty) should pass subscription explicitly.
// Users who need additional meta (e.g. active, touched, dirty) should pass subscription explicitly.
const defaultSubscription: FieldSubscription = { length: true, value: true, error: true }

const isArrayField = (arrayName: string, fieldName: string): boolean =>
fieldName === arrayName || fieldName.startsWith(`${arrayName}[`)

const useFieldArray = (
name: string,
{
Expand Down Expand Up @@ -83,13 +86,51 @@ const useFieldArray = (
format: v => v
})

const needsAggregateActive = !!subscription.active
const needsAggregateTouched = !!subscription.touched
const formState = useFormState({
subscription: {
active: needsAggregateActive,
touched: needsAggregateTouched
}
})

// FIX #167: Don't destructure/spread meta object because it has lazy getters
// Extract length directly from meta when needed
const { meta, input } = fieldState
const length = meta.length

// Create a new meta object that excludes length, preserving lazy getters
const metaWithoutLength = copyPropertyDescriptors(meta, {} as any, ['length'])
const metaWithoutLength = copyPropertyDescriptors(
meta,
{} as any,
[
'length',
...(needsAggregateActive ? ['active'] : []),
...(needsAggregateTouched ? ['touched'] : [])
]
)

if (needsAggregateActive) {
Object.defineProperty(metaWithoutLength, 'active', {
enumerable: true,
get: () =>
typeof formState.active === 'string' && isArrayField(name, formState.active)
})
}

if (needsAggregateTouched) {
Object.defineProperty(metaWithoutLength, 'touched', {
enumerable: true,
get: () => {
const touched = formState.touched
return !!touched &&
Object.keys(touched).some(
(fieldName) => !!touched[fieldName] && isArrayField(name, fieldName)
)
}
})
}

const forEach = (iterator: (name: string, index: number) => void): void => {
// required || for Flow, but results in uncovered line in Jest/Istanbul
Expand Down
Loading