I have a file where I keep some initial values for some form fields base on field type. Some of them are primitive values, like '' or 0 or false
but some of them are non-primitive reference values, like [] or {}
. For example:
INITIAL_VALUES.js
const INITIAL_VALUES= {
SINGLE_CHOICE: '',
MULTIPLE_CHOICE: [],
OBJECT: {},
BOOLEAN: false,
NUMBER: 0,
STRING: ''
};
export default INITIAL_VALUES;
The fact is that I have to be careful when using non-primitive initial values, because since they come as reference, I might change them, and get them a second time with some residual value, instead of being empty.
I've tought about some options to deal with this:
OPTION #1
Make the INITIAL_VALUES.js
export a function that returns the new values object and call that function inside my component.
Example:
getInitialValues.js
function getInitialValues() {
return({
SINGLE_CHOICE: '',
MULTIPLE_CHOICE: [],
OBJECT: {},
// and so on...
});
}
export default getInitialValues;
SomeComponent.js
import getInitialValues from './getInitialValues'
function SomeComponent() {
const INITIAL_VALUES = getInitialValues();
}
OPTION #2
Keep the initial values as an object and everytime I use them, I need to check if it's a non-primitive and create a new one (instead of using the same reference from INITIAL_VALUES
).
Example:
SomeComponent.js
myVariable = INITIAL_VALUES[fieldType];
if (Array.isArray(myVariable)) {
myVariable = [...myVariable]; // CREATE A NEW ARRAY
}
else if (typeof(myVariable) === 'object') {
myVariable = {...myVariable}; // CREATE A NEW OBJECT
}
OPTION #3
Use only non-primitive values. And set null
instead of empty arrays []
and empty objects {}
.
Example:
INITIAL_VALUES.js
const INITIAL_VALUES= {
SINGLE_CHOICE: '',
MULTIPLE_CHOICE: null,
OBJECT: null,
BOOLEAN: false,
NUMBER: 0,
STRING: ''
};
But doing so, whenever I try to populate those fields, I'll need to check if the object/array exists, and create it if it doesn't.
Example
SomeComponent.js
function pushValueToArrayField(newValue) {
setState((prevState) => {
const aux = {...prevState};
if (aux.someArrayField === null) {
aux.someArrayField = [];
}
aux.someArrayField.push(newValue);
return aux;
});
}
What is my best option here?
INITIAL_VALUES.js
file is my exact file. And the options are the consequences that I'll have to embrace whatever road I take. \$\endgroup\$ – cbdeveloper Aug 1 '19 at 10:21