Coherent
Coherent

Reputation: 2113

Update nested react state object with new arbitrary object

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!

Upvotes: 1

Views: 859

Answers (1)

devellopah
devellopah

Reputation: 471

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>

Upvotes: 3

Related Questions