Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to handle a complicated state in react

Background: I am kind of new to react and am learning it, I have made some sites in it but i Highly doubt my way of appraching the problem.

So while handaling a complex state .
For example lets say we have a cart which has a product which is a object and then it contains a quantity key now how can we make changes in that quantity, which will be the best way to do it ??

Example

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const [cart , setcart] = useState([

{_id: "1",
    name:"product1",
    quantity: 2
},
{_id: "2",
    name:"product2",
    quantity: 1
}
]);

lets say we need to update the quantity count of the product with the
id 2 to 5. What we be the best approach, my way of doing it will be.

setcart((items)=>{
const changingItem = items.find((item)=>{return item.id === "2"});
changedItem.quantity = 5;

const newCart = items;
newCart.push(changingItem);

return newCart;
    
})

thank you

>Solution :

setCart(items => items.map(item => item.id === "2" ? {...item, quantity: 5} : item)}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading