2

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 } });
6
  • Can you share how this.state looks? Commented Mar 13, 2018 at 4: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 Commented Mar 13, 2018 at 4: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 Commented Mar 13, 2018 at 4:59
  • 1
    this.setState(state => ({ person: Object.assign({}, state.person, { name: newName }) })); Commented Mar 13, 2018 at 5:00
  • 1
    Please use the search before you ask a new question. Commented Mar 13, 2018 at 5:01

1 Answer 1

1

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;

Sign up to request clarification or add additional context in comments.

1 Comment

Does it have any performance issues if I use this - this.setState(prevState => ({ person: { ...prevState.person, name: newName } }));

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.