-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathenhanced-on-change.js
More file actions
78 lines (63 loc) · 1.86 KB
/
enhanced-on-change.js
File metadata and controls
78 lines (63 loc) · 1.86 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import isEmpty from 'lodash/isEmpty';
import convertType from './convert-type';
/**
* Pick a value from event object and returns it
* @param {Object|Any} event event value returned from form field
*/
const sanitizeValue = (event) => {
if (typeof event === 'object' && event !== null && event.target) {
if (event.target.type === 'checkbox') {
return event;
}
if (event.target.type === 'file') {
return {
inputValue: event.target.value,
inputFiles: event.target.files,
};
}
return event.target.value;
}
return event;
};
/**
* Checks the value and returns undefined if its empty. Converst epmtry strings, arrays and objects.
* If value is empty its overriden to undefined for further processing.
* @param {Any} value Any JS variable to be check if is empty
*/
const checkEmpty = (value) => {
if (typeof value === 'number') {
return false;
}
if (typeof value === 'boolean') {
return false;
}
if (typeof value === 'string' && value.length > 0) {
return false;
}
if (value instanceof Date) {
return false;
}
if (!isEmpty(value)) {
return false;
}
return true;
};
/**
* Casts input value into selected data type
*/
const enhancedOnChange = ({ dataType, onChange, initial, clearedValue, dirty, ...rest }, value, ...args) => {
const sanitizedValue = sanitizeValue(value);
let result;
if (typeof sanitizedValue == 'object' && sanitizedValue !== null && sanitizedValue.target && sanitizedValue.target.type === 'checkbox') {
result = sanitizedValue;
} else {
result = Array.isArray(sanitizedValue)
? sanitizedValue.map((item) => convertType(dataType, sanitizeValue(item)))
: convertType(dataType, sanitizedValue);
}
if (checkEmpty(result)) {
return onChange(clearedValue, ...args);
}
return onChange(result, ...args);
};
export default enhancedOnChange;