DEV Community

loading...

Discussion on: Updating react nested state properties

Collapse
_odagled_ profile image
Un tal ahí
  • this is my initialState

const initialStateInput = {
cabeceraFamilia: {
familia: '',
direccion: '',
telefonos: '',
email: ''
},
motivoConsulta: '',
fechaHora: '',
corresponsables: [],
}

  • The hook or you can replace it with de state class

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

< input type="text" className="form-control" name="cabeceraFamilia.direccion" placeholder="Dirección" defaultValue={infoAgendamiento.cabeceraFamilia.direccion} onChange={actualizarState} / >

Sorry, my English is not the best but i wanted to share my solution ... your article helped me for it