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.
- Iterate the array using map() function.
- Function passed as first argument with in map() should have the condition to decide whether object should be updated or not.
- 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-
- Array is initialized with some product objects.
- 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. - Then set the products state by passing this new array.
- 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.
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
- React Example - Insert New Object in an Array
- How to Loop in React
- props.children in React With Examples
- React Context API With Examples
- React useEffect Hook With Examples
- Shallow Copy Vs Deep Copy in Java Object Cloning
- Java Stream sorted() With Examples
- Java Program to Find Maximum And Minimum Number in a Matrix
- GenericOptionsParser And ToolRunner in Hadoop
No comments:
Post a Comment