How to update Object in state from e.target.name

Viewed 1207

I am trying to input data from a form like this -

<h1>Company Position</h1>
<input
    name="company.position"
    type="text"
    onChange={(e) => functions.setData(e)}
    value={data.company.position}
/>

Into a state Object like this -

const [ form, setValues ] = useState({
    name        : 'Jo Smith',
    email       : 'JoSmith@domain.com',
    phone       : null,
    company     : {
        name     : null,
        position : null
    }
});

Using a handleStateChange function where I pass in the target

const handleStateChange = (e) => {
    e.preventDefault();
    setValues({
        ...form,
        [e.target.name]: e.target.value
    });
};

I cant seem to update the company object inside state I assumed that it would recognize company.name as the target name.

Any help would be appreciated.

2 Answers

e.target.name is company.position, you can't set nested property like obj["company.position"], you'll have to split it :

<input
  name="company.position"
  type="text"
  onChange={e => functions.setData(e)}
  value={data.company.position}
/>;

const handleStateChange = e => {
  e.preventDefault();
  const [section, key] = e.target.name.split(".");

  // section is : company
  // key is : position

  if (key) {
    // if you have nested keys to update
    setValues({
      ...form,
      [section]: {
        ...form[section],
        [key]: e.target.value
      }
    });
  } else {
    // if you're updating on the first level
    setValues({
      ...form,
      [section]: e.target.value
    });
  }
};
const nested = e.target.name.split(".");
    const [section, key] = nested; 
     if(nested.length > 2){
        let total = nested.length;
        let ultimo = nested[total-1];
        saveclinicHistory({
            ...clinicHistory,
            [section]: {//patient
                ...clinicHistory[section],
                [key]: {//address
                    ...clinicHistory[section][key],
                    [ultimo]:e.target.value

                }
            }
        });
Related