-1
I’m making a shopping cart with useReducer
and I can’t change the inCard
for true
and the qty
to add one more to each click.
What am I doing wrong?
import React, { useReducer } from 'react'
import CartContext from './CartContext'
import CartReducer from './CartReducer';
import { ADD_TO_CART, REMOVE_ITEM, SHOW_HIDE_CART } from '../Types'
export default function CartState({children}) {
const initialValues={
showCart:false,
cartItems:[],
}
let [state, dispatch] = useReducer(CartReducer, initialValues);
function addToCart(item){
dispatch({type:ADD_TO_CART, payload:item, ...item.inCart===true})
}
function showHideCart(){
dispatch({type:SHOW_HIDE_CART})
}
function removeItem(id){
dispatch({type:REMOVE_ITEM, payload:id})
}
return (
<CartContext.Provider value={{
showCart:state.showCart,
cartItems:state.cartItems,
addToCart,
showHideCart,
removeItem,
}}>{children}</CartContext.Provider>
)
}
import { ADD_TO_CART, REMOVE_ITEM, SHOW_HIDE_CART } from '../Types'
export default function CartReducer(state, action) {
switch(action.type){
case SHOW_HIDE_CART:{
return{
...state,
showCart:!state.showCart
}
}
case ADD_TO_CART:{
let productsCopy=[...state.cartItems];
productsCopy.forEach((item)=>{
if(item._id===action.payload){
item.qty = item.qty + 1;
item.inCart = true;
}
})
return{
...state,
cartItems:[...productsCopy, action.payload],
}
}
case REMOVE_ITEM:{
return{
...state,
cartItems:state.cartItems.filter((item)=>item._id!==action.payload)
}
}
default:{
return state
}
}
}
It’s like this in Context:
{
"value": {
"showCart": false,
"cartItems": [
{
"id": "1",
"name": "MOLETOM VERMELHO CABRAL",
"image": "./assets/moletomVermelho.jpg",
"zomImage": "./assets/moletomVermelhoZom.jpg",
"previousPrice": 345.9,
"currentPrice": 242.1,
"inCart": false,
"qty": 0,
"colors": "[{…}, {…}]",
"size": "{g: true, m: false, p: true, xg: true}"
}
],
"addToCart": "ƒ addToCart() {}",
"showHideCart": "ƒ showHideCart() {}",
"removeItem": "ƒ removeItem() {}"
},
"children": "<App />"
}