December 5, 2022

React Example - Update Object in an Array of Objects

It is a very common requirement to update one or more objects in an array of objects in your React application. What you need to keep in mind is that the you should not mutate an array when you store them in state. You should rather create a new array with the required changes and set state to use this new array.

Update object in array of objects

If you want to modify one or more items of an array, you can use map() to create a new array. Steps are as given below.

  1. Iterate the array using map() function.
  2. Function passed as first argument with in map() should have the condition to decide whether object should be updated or not.
  3. If condition is satisfied then update that object otherwise return the object as is. That way you will have a new array with all the objects including updated one.

As an example, let's have a shopping cart with certain products added. On the click of the button increase or decrease the product count.

import { useState } from "react";

const INITIAL_PRODUCTS = [{
    id: 1,
    name: 'Samosa',
    count: 5,
  }, 
  {
    id: 2,
    name: 'Roti',
    count: 4,
  }, 
  {
    id: 3,
    name: 'Chicken Tikka Masala',
    count: 2,
  },
  {
    id: 4,
    name: 'Matar Paneer',
    count: 1,
  }];

const ShoppingCart = () => {
    const [products, setProducts] = useState(INITIAL_PRODUCTS);
    const handleIncreaseClick = (productId) => {
        const updatedProducts = products.map(product => {
            // update count property of the matching object
            if(product.id === productId){
              return {...product, 
                      count:product.count + 1};
            }else{
              // return object unchanged
              return product;
            } 
          });
        setProducts(updatedProducts);
    }
    const handleDecreaseClick = (productId) => {
        let updatedProducts = products.map(product => {
            if(product.id === productId){
              return {...product, 
                      count:product.count - 1};
            }else{
              return product;
            } 
        });
        updatedProducts = updatedProducts.filter(p => p.count > 0);
        setProducts(updatedProducts);
    }
    return (
        <ul>
            {
                products.map(product => (
                    <li key={product.id}>
                        {product.name}
                        -
                        {product.count}
                        <button onClick={()=> {
                            handleIncreaseClick(product.id)
                        }}>+</button>
                        <button onClick={()=> {
                            handleDecreaseClick(product.id)
                        }}>-</button>
                    </li>
                ))
            }
        </ul>
    );
}

export default ShoppingCart;

Important points to note in the code are-

  1. Array is initialized with some product objects.
  2. Clicking the ‘+’ button triggers the handleIncreaseClick() function with the id of the product passed as an argument. In the handleIncreaseClick() function create a new array by going through all the products, the product for which the id matches increase the count by 1, otherwise return the product without any change.
  3. Then set the products state by passing this new array.
  4. Clicking the ‘-’ button triggers the handleDecreaseClick() function with the id of the product passed as an argument. If the product id matches, decrease the count by 1. One more thing is to later check for the products with count as 0 to remove them from the array. For that filter() is used.
Update object in array of objects

That's all for the topic React Example - Update Object in an Array of Objects. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment