I\'m trying to organize my state by using nested property like this:
this.state = {
someProperty: {
flag:true
}
}
But updating
This is my initialState
const initialStateInput = {
cabeceraFamilia: {
familia: '',
direccion: '',
telefonos: '',
email: ''
},
motivoConsulta: '',
fechaHora: '',
corresponsables: [],
}
The hook or you can replace it with the state (class component)
const [infoAgendamiento, setInfoAgendamiento] = useState(initialStateInput);
The method for handleChange
const actualizarState = e => {
const nameObjects = e.target.name.split('.');
const newState = setStateNested(infoAgendamiento, nameObjects, e.target.value);
setInfoAgendamiento({...newState});
};
Method for set state with nested states
const setStateNested = (state, nameObjects, value) => {
let i = 0;
let operativeState = state;
if(nameObjects.length > 1){
for (i = 0; i < nameObjects.length - 1; i++) {
operativeState = operativeState[nameObjects[i]];
}
}
operativeState[nameObjects[i]] = value;
return state;
}
Finally this is the input that I use