0

I have a state with nested object in it. I need to setState() the state value with the onChange event with every word I write in the input section.

i tried to update directly with this.state.rootProperty.childProperty but it creates a new state rootProperty.childProperty: "value i wrote".

Any ideas on how to setState those nested state? Thanks.

    this.state = {
      taskData: "",
      memberData: "",
      judul: "",
      kode: "",
      ketua_team: "",
      koordinator: "",
      tgl_mulai: "",
      tgl_selesai: "",
      detail1: {
        no: "",
        tiket: "",
        deskripsi: "",
        target: "",
        auditor: "",
        nil_peg: "",
        nil_at: "",
        nil_at_at: "",
      },

//this is my state, i need to update auditor value with handler

onChangeNest(e) {
    this.setState({ [e.target.name]: e.target.value });
  }

//and my input props
 <input
 type="text"
 placeholder="auditor"
 name="detail1.auditor"
 onChange={this.onChangeNest}
 ></input>

2 Answers2

0

setState doesn't handle updates on nested properties. One of the possible solutions is to copy the entire state (create a dummy object), modify it and update state with the fully modified object.

It's really well explained in this answer. You might find it helpful:

How to update nested state properties in React

0

If it is only for 1 level nested object, you could try the following:

  onChangeNest = (e) => {
    let targetName = e.target.name
    if (targetName.includes(".")) {
      let splt = targetName.split(".")
      let oldObj = {...this.state[splt[0]]}
      oldObj[splt[1]] = e.target.value
      this.setState({ [splt[0]]: oldObj })
    } else {
      this.setState({ [targetName]: e.target.value })
    }
  }
Apostolos
  • 10,033
  • 5
  • 24
  • 39