Created
February 14, 2023 02:17
-
-
Save oelbaga/b77d38eb9706b5ff01ea909e5aa24f81 to your computer and use it in GitHub Desktop.
Update Array of Objects in React State
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//add object to state | |
setProducts([ | |
...products, | |
{ | |
product_id: newproduct.product_id, | |
product_name: newproduct.product_name, | |
}, | |
]); | |
//update object to state | |
const productsStateAfterUpdate = products.map((product) => { | |
if (product.product_id === productIdToUpdate) { | |
const productUpdated = { | |
...product, | |
product_name: productUpdatedName, | |
}; | |
return productUpdated; | |
} else { | |
return { | |
...product, | |
}; | |
} | |
}); | |
setProducts(productsStateAfterUpdate); | |
//remove object from state | |
setProducts(products.filter((a) => a.product_id !== idToRemove)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks