1

How can I update a value within a react state object when that value is an object? Example:

this.state = { nestedObj: { x: 0, y: 5 } };

at a later time, I want to update that nestedObj with an arbitrary object based on the object created from a JSON.parse based on user input.

I try the following and it does not work:

const newObj = {nestedObj: { x: 0, arbitraryKey: 'bla', anotherOne: { h: 0 }}};
this.setState(newObj);

I would really like to just blow away whatever object resides at this.state.nestedObj and replace it with whatever object is defined at newObj. How can I do that? I have other keys in my this.state so it would be ideal if this only affected the nestedObj but I'm not super picky. Thanks!

1
  • did you tried this.setState({nestedObj: newObj})? Commented Oct 11, 2016 at 3:20

1 Answer 1

3

class Main extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      obj: {a: 'hello', b: 'world'}
    };
  }
	
  componentDidMount() {
    console.log('obj is initialized to: ', this.state.obj);
  }
	
  handleClick = () => {
	const value = Math.random().toFixed(2);
	this.setState({
		obj: {a: value, b: value}
	}, () => console.log('obj is changed to: ', this.state.obj));
  };

  render() {
	return <button onClick={this.handleClick}>button</button>
  }
}

ReactDOM.render(
	<Main />, 
	document.getElementById('root')
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.