Hello I have a very complex form with many nested objects and I am wondering how to update a field in the nested objects without writing one million lines of code, this is what I currently have. I have heard about the library called immer but know nothing about it.
this is the initial value of the object
const initialFormState = {
name: "",
address: {
street1: "",
street2: "",
city: "",
state: "",
zip: "",
country: "",
gps: {
lat: "",
lng: ""
}
},
clientId: "",
contact: {
userId: "",
firstName: "",
lastName: "",
jobTitle: ""
},
isActive: true,
requiresAction: true,
details: {
lastInspectionDate: "",
lastMaintenanceDate: "",
employeesTrained: 0,
phone: "",
companyManager: {
name: "",
title: "",
phone: "",
email: ""
},
companyOwner: {
name: "",
title: "",
phone: "",
email: ""
},
companyContact: {
name: "",
title: "",
phone: "",
email: ""
},
companyType: "",
locations: 0,
foo: 0,
bar: 0,
foo2: ""
}
}
and my reducer function and state variables
const [formState, dispatch] = useReducer(formReducer, initialFormState)
const formReducer = (prevState: any, action: any) => {
switch (action.type) {
case 'update-name':
return { ...prevState, name: action.payload}
console.log()
break
case 'update-address':
return { ...prevState, address: { ...prevState.address, [action.field]: action.payload}}
break
case 'update-contact':
return { ...prevState, contact: { ...prevState.contact, [action.field]: action.paylod}}
break
case 'update-client-id':
return { ...prevState, clientId: action.payload}
break
case 'update-isActive':
return { ...prevState, isActive: action.payload }
break
case 'update-requiresAction':
return { ...prevState, requiresAction: action.payload}
break
case 'update-details':
return { ...prevState, details: { ...prevState.details, [action.field]: action.payload}}
}
}
but everytime I go to update the contact object, I keep getting undefined. This is what I am passing in the onChange for the text fields, I will use street line 1 as an example
onChange={(e) => { dispatch({ type: 'update-contact', field: 'street1', payload: e.target.value })}}