I am trying to do some kind of online shop for myself and I got a problem.
I want to render my shopping cart size in the NavBar
component (which is on every page).
I created a Cart Items service where I put all my added items, and it also has functions to addItem
, removeItem
, getCart
, getCartSize
.
When I click on Add/Remove on specific product, I would like to do that the value on NavBar
with cart size would be changing depending on the cart size (from getCartSize
method). I already tried to use useEffect
hook, but it does not recognize when the value of cartSize
is changed, how can I do that?
This is what I have done already.
navbar.jsx
:
//...
//...
import {getTotalCount} from '../../services/myCart';
export default function Navbar() {
// ...
const [count, setCount] = useState();
useEffect(() => {
setCount(getTotalCount());
console.log('counto useeffect');
},[getTotalCount()]);
//},[getTotalCount]); doesn'work also.
//},[count]); doesn'work also.
return (
<>
<header className="navbar">
<Link className="navbar__list-item__home-icon" to="/"><span><FaHome/></span></Link>
<Link className="navbar__list-item" to="/products">Products</Link>
<h2>cart size--> {count}</h2>
<Link className="navbar__list-item__cart-img" to="shopping-cart"><span><FaShoppingCart/></span></Link>
</header>
</>
);
}
myCart.js
all functions work fine and I call them when I click add/remove button in on my component in the products page.
var InTheCart = [
];
var totalCount = 0;
export function AddToCart(item) {
// ... logic
totalCount++;
}
export function ContainsInTheCart(id) {
return InTheCart.findIndex(x=> x.item.id == id) != -1 ? true: false;
}
export function RemoveFromCart(id) {
// ... logic
totalCount--;
}
export function getCart() {
return InTheCart;
}
export function getTotalCount() {
return totalCount;
}