1) You don't need useEffect nor useState to grab the total value in the cart. You can grab that value by using the cart already in state.
2) Anytime updating state which depends on the previous state its a good practice to use functional updates.
Refactored it a bit to address both points mentioned before:
importReactfrom"react";constitems=[{id:1,name:"overwatch",price:20,},{id:2,name:"minecraft",price:32,},{id:3,name:"fortnite",price:51,},];constShop=()=>{const[cart,setCart]=React.useState([]);constcartTotal=cart.reduce((total,{price=0})=>total+price,0);constaddToCart=(item)=>setCart((currentCart)=>[...currentCart,item]);constremoveFromCart=(item)=>{setCart((currentCart)=>{constindexOfItemToRemove=currentCart.findIndex((cartItem)=>cartItem.id===item.id);if(indexOfItemToRemove===-1){returncurrentCart;}return[...currentCart.slice(0,indexOfItemToRemove),...currentCart.slice(indexOfItemToRemove+1),];});};constamountOfItems=(id)=>cart.filter((item)=>item.id===id).length;constlistItemsToBuy=()=>items.map((item)=>(<divkey={item.id}>{`${item.name}: $${item.price}`}<buttontype="submit"onClick={()=>addToCart(item)}>Add</button></div>));constlistItemsInCart=()=>items.map((item)=>(<divkey={item.id}>
({amountOfItems(item.id)} x ${item.price}) {`${item.name}`}<buttontype="submit"onClick={()=>removeFromCart(item)}>Remove</button></div>));return(<div>
STORE
<div>{listItemsToBuy()}</div><div>CART</div><div>{listItemsInCart()}</div><div>Total: ${cartTotal}</div><div><buttononClick={()=>setCart([])}>Clear</button></div></div>);};exportdefaultShop;
I agree. This is how I’d do it in practice. I wanted to explain useEffect in the article so I created a use case where I could use it as well as it’s dependency array. I’ll heart this so people can see this as well.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Some quick notes:
1) You don't need
useEffect
noruseState
to grab the total value in the cart. You can grab that value by using the cart already in state.2) Anytime updating state which depends on the previous state its a good practice to use functional updates.
Refactored it a bit to address both points mentioned before:
I agree. This is how I’d do it in practice. I wanted to explain useEffect in the article so I created a use case where I could use it as well as it’s dependency array. I’ll heart this so people can see this as well.