DEV Community

Rishabh Jain
Rishabh Jain

Posted on

How to update an object state in React.Js

This would be a continuation to basic react state change, Let's learn how to modify objects now with similar examples.

Let's learn the correct way to do it today...

Let's take following cases.

  1. Object change
  2. Object inside an Object.
  3. Object inside an array inside an object.
const [user, setUser] = useState({ id: 1, username: 'user01' });

const Component = () => {
    // Method 1 -> Use object destructure
    const method1 = () => {
        const newUser = {
          ...user,
          username: `user02`
        };

        setUser(newUser);
    };

    // Method 2 -> Use Object.assign method.
    const method2 = () => {
        const newUser = Object.assign({}, user, { username: 'user02' });
        setUser(newUser);
    };

    return <pre>{JSON.stringify(user, null, 4)}</pre>;
}
Enter fullscreen mode Exit fullscreen mode

With method 1 we are using object destructuring to copy the original object and then append the property at the last to overwrite it.

With method 2 we are using Object.assign to copy the object and then merging it with a new object. In Object.assign the priority is right to left, right most objects gets the higher priority.

Let's update an object inside an object process is very similar but let's review that as well.

const [user, setUser] = useState({ id: 1, username: 'user01', address: { city: 'Mohali', country: 'India' } });

const Component = () => {
    // Method 1 -> Use object destructure
    const method1 = () => {
      const newUser = {
            ...user,
        address: {
                ...user.address,
                city: 'Chandigarh'
            }
      };

      setUser(newUser);
    };

    // Method 2 -> Use Object.assign method.
    const method2 = () => {
        const newUser = Object.assign({}, user, { address: Object.assign({}, user.address, { city: 'Chandigarh' }) });
      setUser(newUser);
    };

    return <pre>{JSON.stringify(user, null, 4)}</pre>;
}
Enter fullscreen mode Exit fullscreen mode

Lastly let's update an object inside an array inside an object for this we will combine array update and object update together.

const [user, setUser] = useState({ id: 1, username: 'user01', children: [{ id: 1, username: 'child1' }, { id: 2, username: 'child2' } ] });

const Component = () => {
    // Method 1 -> Use object destructure
    const method1 = (childIndex) => {

        // Let's create a copy of the array.
        const child = [...user.children];

        // Updating the {childIndex} of the copy based on the previous methods we discussed.
        child[childIndex] = { ...child[childIndex], username: 'updatedChild' };

      const newUser = {
            ...user,
        children: child
      };

      setUser(newUser);
    };

    // Method 2 -> Using splice method.
    const method2 = (childIndex) => {
        // Let's create a copy of the array.
        const child = [...user.children];

        // Updating the {childIndex} of the copy based on the previous methods we discussed.
        child.splice(childIndex, 1, { ...child[childIndex], username: 'updatedChild' });

      const newUser = {
            ...user,
        children: child
      };

      setUser(newUser);
    };

    return <pre>{JSON.stringify(user, null, 4)}</pre>;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)