-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathuseGetArrayInputNewItemDefaults.ts
More file actions
51 lines (48 loc) · 1.81 KB
/
useGetArrayInputNewItemDefaults.ts
File metadata and controls
51 lines (48 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { Children, isValidElement, useRef, type ReactNode } from 'react';
import set from 'lodash/set.js';
import { FormDataConsumer } from '../../form/FormDataConsumer';
import type { ArrayInputContextValue } from './ArrayInputContext';
import { useEvent } from '../../util';
export const useGetArrayInputNewItemDefaults = (
fields: ArrayInputContextValue['fields']
) => {
const initialDefaultValue = useRef<Record<string, unknown>>({});
if (fields.length > 0) {
const { id, ...rest } = fields[0];
initialDefaultValue.current = rest;
for (const k in initialDefaultValue.current)
initialDefaultValue.current[k] = null;
}
return useEvent((inputs?: ReactNode) => {
if (
Children.count(inputs) === 1 &&
isValidElement(Children.only(inputs)) &&
// @ts-ignore
!Children.only(inputs).props.source &&
// Make sure it's not a FormDataConsumer
// @ts-ignore
Children.only(inputs).type !== FormDataConsumer
) {
// ArrayInput used for an array of scalar values
// (e.g. tags: ['foo', 'bar'])
return '';
}
// ArrayInput used for an array of objects
// (e.g. authors: [{ firstName: 'John', lastName: 'Doe' }, { firstName: 'Jane', lastName: 'Doe' }])
const defaultValue = { ...initialDefaultValue.current };
Children.forEach(inputs, input => {
if (
isValidElement(input) &&
input.type !== FormDataConsumer &&
input.props.source
) {
set(
defaultValue,
input.props.source,
input.props.defaultValue ?? null
);
}
});
return defaultValue;
});
};