Skip to content

Instantly share code, notes, and snippets.

@oelbaga
Created February 14, 2023 02:17
Show Gist options
  • Save oelbaga/b77d38eb9706b5ff01ea909e5aa24f81 to your computer and use it in GitHub Desktop.
Save oelbaga/b77d38eb9706b5ff01ea909e5aa24f81 to your computer and use it in GitHub Desktop.
Update Array of Objects in React State
//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));
@najib2050
Copy link

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment