How To Update Nested Properties In A State Object In React

Update nested properties in a State object in React

This article helps you update nested properties in a state object in React. Check out the information we provide.

Update Nested Properties In A State Object In React

Method 1 – Use the spread operator

The spread syntax is a useful ES6 concept. Let’s learn more about the concept and its uses. The syntax is very simple: ‘‘. It allows you to copy or update an object.

Now let’s apply this to our problem.

import './App.css';
import {useState} from 'react';

export default function App() {
  
  const [store, setStore] = useState({
    brand: 'Highland Coffee',
    foundedYear: 1999,
    branches: {
      address1: ['Ha Noi',12],
      address2: ['Ho Chi Minh', 15],
      address3: ['Da Nang', 10],
      address4: []
    },
  });

  const updateProperties = () => {
    setStore(currentState => {

      return {
        ...currentState,
        branches: {
          ...currentState.branches,
          address4: ['Hai Phong', 8],
          address5: ['Hue', 6]
        },
      };
    });
  };

  const result = JSON.stringify(store)

  return (
    <div className='container'>      
      <p><b>{result}</b></p>
      <hr></hr>
      <button className='btn btn-primary' onClick={updateProperties }>Update properties</button>
    </div>
  );
}

Output:

The purpose of using the spread syntax (…) is to unpack all the key-value pairs of the object into a new object. So in the above example, we did the same thing. To update the properties, we will override them, or you can also declare new properties for the object.

Look at the output. Let me explain it. By using the spread operator, the property ‘address4‘ has overwritten itself. 

Because as I said above, the two properties have the same name. When re-declared, the old attribute will be overwritten to the newest value. Additionally, the property ‘address5’ is also newly added to the object because there was no property named ‘address5‘ before in the object.

A note for you is that we must not directly modify the state object under any circumstances.

Method 2 – Another approach for you

Basically, this method is completely the same as the first method. 

How we use the spread syntax to work with objects is different here. 

import './App.css';
import {useState} from 'react';

export default function App() {
  

  const [store, setStore] = useState({
    brand: 'Highland Coffee',
    foundedYear: 1999,
    branches: {
      address1: ['Ha Noi',12],
      address2: ['Ho Chi Minh', 15],
      address3: ['Da Nang', 10],
      address4: []
    },
  });

  const updateProperties = () => {
    setStore(currentState => {
      const branches = {...currentState.branches}   
      branches.address4 = ['Hai Phong', 8]
      branches.address5 = ['Hue', 6]
      return {
        ...currentState,
        branches}
    });
  };

  const result = JSON.stringify(store)

  return (
    <div className='container'>      
      <p><b>{result}</b></p>
      <hr></hr>
      <button className='btn btn-primary' onClick={updateProperties }>Update properties</button>
    </div>
  );
}

In this approach, we copy the nested property of the object and make direct edits to that new object.

The result is, of course, the same as the example above. There is absolutely nothing wrong with this method. However, I do not recommend using this method. The reason is that it will make your program look more confusing.

Summary

I hope you understand how we can update nested properties in a State object in React through the above simple example. Thank you for reading to the end.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *