AMHNewsHub

Updating an object with setState in React

December 15, 2022 By sanxbot00

To update an object with setState in React, you can use the setState method, which is a method available on React components. This method takes an object containing the new values for the state, and merges those values with the current state. Here’s an example of how you might use setState to update an object in React:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {
        name: 'John Doe',
        age: 30
      }
    };
  }

  handleClick = () => {
    this.setState({
      data: {
        ...this.state.data,
        age: 35
      }
    });
  }

  render() {
    return (
      <div>
        <p>Name: {this.state.data.name}</p>
        <p>Age: {this.state.data.age}</p>
        <button onClick={this.handleClick}>Update Age</button>
      </div>
    );
  }
}

In the above example, we have a component called MyComponent that has a data object in its state. When the user clicks the “Update Age” button, the handleClick method is called, which uses setState to update the age property of the data object in the state.

It’s important to note that setState does not immediately update the state of the component. Instead, it schedules an update to be performed asynchronously. This means that if you want to do something with the updated state immediately after calling setState, you should use the second argument to setState, which is a callback function that will be called after the state has been updated.

this.setState({
  data: {
    ...this.state.data,
    age: 35
  }
}, () => {
  // Do something with the updated state here
});

You can learn more about the setState method in the React documentation.