How to Update an Object Inside another Object in React

Updated 2 weeks ago admin Javascript / React

In today's lesson, we will see how to update an object inside another object in React. Let's assume that we have an object 'order' inside this object, we have another object, which is the 'user' who made the order, and we want to update his address. So, how can we do that?

Update the user's address

So, as we said before, to update the user's address, you can do that using the code below:

const [order, setOrder] = useState({
  product: 'Iphone 12',
  price: 1200,
  qty: 1,
  user: {
    name: 'john doe',
    address: ''
  }
});

const updateUserAddress = (newAddress) => {
   setOrder({...order, user: {address: newAddress}})
}