'Why is my useEffect not being called when I take a item out of my cart in React?
I am doing a simple food ordering web app with React and for some reason, I can't get my useEffect to run when the cart is changed with the X button to delete an item from the cart. This is true for both the heading cart counter and for the total amount. Both of these change when I am adding the item to the cart, but don't decrement with the remove button. I am able to delete the item from the cart and the state, but still nothing. I have tried changing my useReducer to it, but still nothing. Any help would be wonderful.
const initialState = 0;
const reducer = (state, action) => {
switch (action) {
case "increment":
return state + 1;
case "decrement":
return state - 1;
case "reset":
return initialState;
default:
return state;
}
};
export const CountContext = React.createContext();
const Home = (props) => {
const [cart, setCart] = useState([]);
const [count, dispatch] = useReducer(reducer, initialState);
const {isVisible, toggleModal} = useModal();
let totalPrice;
let cartCounter ;
const cartUpdaterHandler = (cartItem) =>{
setCart([...cart, cartItem]);
cartItem= cartItem;
}
useEffect(() => {
cartCounter = cart.length;
totalPrice = cart.reduce((acc, {price}) => parseFloat(acc) + parseFloat(price), 0).toFixed(2);
}, [cart, cartCounter])
const modalHandler = () => {
toggleModal(true)
}
const removeCI = ( cartItemId) => {
setCart(cart.filter((cartItem) => cartItem !== cartItemId))
cartCounter = cart.length -1
console.log(cartCounter)
}
return (
<CountContext.Provider
value={{ countState: count,
countDispatch: dispatch,
currentCart: cart
}}
className={classes.contextProvider}
>
{isVisible && (
<CartModal
overlayClassName="custom_overlay"
isVisible={isVisible}
hideModal={toggleModal}
currentCart={cart}
totalPrice={totalPrice}
remove={removeCI}
/>
)}
<Header cart={cart} cartCounter={cart} modal={modalHandler}/>
<Intro />
<MealForm onAdd={cartUpdaterHandler} />
{/* <Cart /> */}
{/* <CartModal isVisible={isVisible} hideModal={toggleModal} currentCart={cart} totalPrice={totalPrice}/> */}
</CountContext.Provider>
)
}
export default Home;
const CartHeader = (props) => {
const [modal, setModal] = useState(false)
const {isVisible, toggleModal} = useModal();
// const cartCtx = useContext(CartContext);
const countContext = useContext(CountContext);
const curCart = [props.cart]
return (
<React.Fragment >
<CartIcon />
<a onClick={props.modal}>Your Cart</a>
{/* <CartModal isVisible={isVisible} hideModal={toggleModal} /> */}
{/* <div className='cart-header-number'>{props.counter}</div> */}
<div className='cart-header-number'>{countContext.countState}</div>
</React.Fragment>
)
}
export default CartHeader;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
