0

I'm trying to update the property 'name' of my object person using setState. But it doesn't seem to work. I'm getting the 'newName' through user input.

What am I missing here?

this.setState({ person: { name: newName } });
Sunny
  • 734
  • 1
  • 12
  • 31
  • Can you share how `this.state` looks? – Learn on hard way Mar 13 '18 at 04:58
  • 1
    Some more context would be a big help, the full source of your component for example. At the very least, the shape of your state and the function that this `setState` is being done in. I suspect it's an issue with how `setState` only merges in the top level of object keys – kingdaro Mar 13 '18 at 04:58
  • by this way, person object will loose all other keys, only name will be their after update, check this answer: [updating an object with setState](https://stackoverflow.com/questions/43638938/updating-an-object-with-setstate-in-react/43639228#43639228) – Mayank Shukla Mar 13 '18 at 04:59
  • 1
    `this.setState(state => ({ person: Object.assign({}, state.person, { name: newName }) }));` – Felix Kling Mar 13 '18 at 05:00
  • 1
    Please use the search before you ask a new question. – Felix Kling Mar 13 '18 at 05:01
  • Here's how my person object looks like ... person { name: John, age: 25, address: {}, qualification: {} } – Sunny Mar 13 '18 at 05:14

1 Answers1

0

class TestJS extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            person : {name : "DefaultName", age : 56}
        }
    }

    componentDidMount(){
        this.setState(state => ({ person: Object.assign({}, state.person, { name: "sdsds" }) }));
    }

    render() {
        return(
            <div id="root">
                {this.state.person.name}
                {this.state.person.age}
                <p>Hello world</p>
            </div>

        );
    }
}

export default TestJS;
Harsh Makadia
  • 2,637
  • 5
  • 22
  • 37
  • Does it have any performance issues if I use this - this.setState(prevState => ({ person: { ...prevState.person, name: newName } })); – Sunny Mar 13 '18 at 05:16