0

How do I use setState if am having nested object. I have a json list using that I update this state. but Suppose if I want to update only a Phone Number field in this state then how do I make it. Below code gives me error

this.setState(prevState => ({
   myData: {
             ...prevState.myData,
             user: { ...prevState.myData.user, PhoneNumber: value }
            }
}));

interface IData  {
    ID:number,
    usage:string,
    user:IUser
}

interface IUser{
    name:string,
    PhoneNumber:number
}
Domino987
  • 8,475
  • 2
  • 15
  • 38
Ankit Jayaprakash
  • 1,040
  • 3
  • 15
  • 31
  • What's the error you're getting? – Clarity Jul 23 '19 at 10:07
  • https://stackoverflow.com/questions/43040721/how-to-update-nested-state-properties-in-react – klugjo Jul 23 '19 at 10:07
  • Possible duplicate of [How to update nested state properties in React](https://stackoverflow.com/questions/43040721/how-to-update-nested-state-properties-in-react) – klugjo Jul 23 '19 at 10:07

1 Answers1

0

The simplest way of doing this is to create a clone of the object that you want to update, then update that clone using javascript as you desire, then set the state using that clone object. Like this:

let clone = {...objectInStateToUpdate};
  // Do operations on clone as desired
this.setState({objectInStateToUpdate: clone});
  // or if you named the cloned same as your object
this.setState({clone});

Hope it helps!

Harshit Agarwal
  • 2,308
  • 2
  • 15
  • 23