i have 2 useStates i want to append both when i call SubmitData
allValues has many datas name ,age ,sex etc.. i want add domestic also into allvalues
const changeHandler = (e) => {
setAllValues({ ...allValues, [e.target.name]: e.target.value });
};
const SubmitData = () => {
console.log(domestic);
const formData = { ...allValues };
if (!domestic) {
formData.domestic = domestic;
}
var custumer = parseInt(id);
if (!custumer) {
formData.customer = custumer;
}
when allValues is empty and i only pass value of domestic i am getting the floowlowing error
TypeError: Cannot set properties of undefined (setting 'domestic')
UPDATED
Since you have been facing undefined problem, I update the logic a bit
const formData = {...allValues}
if (!domestic_voilence) {
formData.domestic = domestic_voilence;
}
const customer = id ? parseInt(id) : null;
if (!customer) {
formData.customer = customer;
}
//TODO: submit your form data instead
ORIGINAL
You can simply do this way
if(domestic !== null) {
allValues.domestic = domestic
}
It will automatically populate your domestic data to allValues.
If you want to have formData as the main variable
const formData = {
...allValues,
}
if(domestic !== null) {
formData.domestic = domestic
}
ES5 version
const formData = Object.assign({}, allValues);
if(domestic !== null) {
formData.domestic = domestic
}