How to update an object with setState in ReactJS?


ReactJS allows us to define a state object for every component. In the state object, we can add the different variables as a property of the state object. After that, we can use the state variables inside the component to render or perform other operations in the component.

This tutorial will teach us to create a state object for the component and update it with various values.

Use the setState to update the object in ReactJS

The state object is used with the class components in ReactJS. Using the setState() method, we can update the state object.

Syntax

Users can follow the syntax below to use the setState() method to update the object in ReactJS.

this.setState({
      student: {
        ...this.state.student,
        fees: new_value,
      },
    });

In the above syntax, we have passed the updated student object as a parameter of the setState() method. Also, we have used the spread operator with student objects.

Example

In the example below, we have created the state object inside the class component. The state object contains the number property and is initialized with the random number using the Math.random() method.

Whenever the user clicks the button, we invoke the changeNumber function. In the changeNumber() function, the setState() method is used to update the state object. We have passed the object with a new random number as a parameter of the setState() method.

import React, { Component } from "react";
// creating the class component
class App extends Component {
  state = {
    number: Math.random(),
  };

  // Method to update the object
  changeNumber = () => {
    this.setState({ number: Math.random() });
  };

  render() {
    return (
      <div>
        <h2>
          {" "}
          Generating the random number and updating it using the{" "}
          <i> setState() </i> method.{" "}
        </h2>
        <h3
          style={{
            border: "2px solid yellow",
            borderRadius: "10px",
            width: "22rem",
            height: "5rem",
            backgroundColor: "blue",
            color: "white",
            fontSize: "2rem",
          }}
        >
          <span>{this.state.number}</span>
        </h3>
        <button
          onClick= {this.changeNumber}
          style = {{
            border: "2px solid green",
            borderRadius: "10px",
            padding: "0.5rem 1rem",
            backgroundColor: "yellow",
            color: "black",
            fontSize: "1rem",
          }}
        >
          {" "}
          Generate random values{" "}
        </button>
      </div>
    );
  }
}

export default App;

Output

Example

In the example below, the table object contains the nested object as a value of student property. The student object contains the id, name, age and fee properties.

After that, whenever the user presses the button, it invokes the changesFees() function, which changes only the value of fee properties in the student object. Users can see how we have used the spread operator inside the setState() method to keep other values the same in the student object.

import React, { Component } from "react";
// creating the class component
class App extends Component {
  state = {
    student: {
      id: "123qwe",
      name: "Shubham",
      age: 22,
      fees: 200000,
    },
  };

  // Method to update the object
  changeFees = () => {
    
    this.setState({
      student: {
        ...this.state.student,
        fees: this.state.student.fees + this.state.student.fees * 0.2,
      },
    });
  };

  render() {
    return (
      <div>
        <h2>
          {" "}
          Updating the fees in the student object using the setState method
          <i> setState() </i> method.{" "}
        </h2>
        <h3
          style = {{
            border: "2px solid yellow",
            borderRadius: "10px",
            width: "22rem",
            height: "5rem",
            backgroundColor: "blue",
            color: "white",
            fontSize: "2rem",
          }}
        >
          <span> {this.state.student.fees} </span>
        </h3>
        <button
          onClick = {this.changeFees}
          style = {{
            border: "2px solid green",
            borderRadius: "10px",
            padding: "0.5rem 1rem",
            backgroundColor: "yellow",
            color: "black",
            fontSize: "1rem",
          }}
        >
          {" "}
          Change the fees of student{" "}
        </button>
      </div>
    );
  }
}

export default App;

Output

Use the hooks in ReactJS to update the state of the object

The setState() method is an old way to update state objects in ReactJS. In recent years, hooks have been introduced in ReactJS, which we can use to update an object or variable values in React.

Syntax

Users can follow the syntax below to update state objects using the hooks.

  const [state, setState] = useState({
    prop1: "Value1",
    prop2: "value2",
    prop3: "value3",
  });

setState((state) => ({ ...state, prop3: value }));

The setState() method is defined in the above syntax to update the state object. In the setState() method, we have passed the callback function as a parameter.

Example

In the example below, we have used the function component in ReactJS. We have used the state to store the object and setState to update the state object. However, users can give other names to the state and setState.

We are taking the user input for the value of the prop3 property of the state object. After that, we change the value of the prop3 property of the state object in the handleSubmit() function. In the setState(), we get the previous state as a callback parameter, and we use it with the spread operator in the callback function.

import React, { useState } from "react";
const App = () => {
  const [state, setState] = useState({
    prop1: "Value1",
    prop2: "value2",
    prop3: "value3",
  });
  const [value, setValue] = useState("");

  function handleValue(e) {
    // handle the value
    let new_value = e.target.value;
    setValue(new_value);
  }

  function handleSubmit() {
    // updating the state object
    setState((state) => ({ ...state, prop3: value }));
  }
  return (
    <div>
      <h2>
        {" "}
        Using the <i> useState hooks </i> to update the objects in the state
      </h2>
      <h3>Enter the value to change for the prop3 of state object. </h3>
      <input type = "text" value = {value} onChange = {handleValue} />
      <div style = {{ color: "blue", fontSize: "1.5rem" }}>
        The key value pairs of the state object are : prop1 - {state.prop1},
        prop2 - {state.prop2}, prop3 - {state.prop3}
      </div>
      <button
        onClick = {handleSubmit}
        style = {{
          margin: "1rem 0",
          padding: "0.5rem 1rem",
          backgroundColor: "lightgreen",
          border: "2px dotted blue",
          borderRadius: "10px",
          color: "black",
          fontSize: "1.3rem",
          padding: "0.5rem",
        }}
      >
        Submit
      </button>
    </div>
  );
};

export default App;

Output

We learned to use the setState() method with a function component and class component to update the state object. Nowadays, users can use the functional component as hooks provide better functionality to update the state objects.

Updated on: 08-Sep-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements