const [Cart, setCart] = useState([]);
const [Csize, setSize] = useState(0);
useEffect(() => {
setSize(Cart.length);
console.log("updated size", Csize); // Log the updated size directly
}, [Cart]);
const handleClick = (item) => {
// Check if the item is already present in the cart
const isPresent = Cart.some(cartItem => cartItem.id === item.id);
if (isPresent) {
return;
}
// Update Cart state by adding the new item
setCart([...Cart, item]);
console.log(Csize)
}
<ul>
<Link to="/Cart" className="bikescart"><ShoppingCart color="#ffffff" size={35}/>
<span>{Csize}</span>
</Link>
</ul>
This is bikes.jsx file.
And what i am getting in console is everytime i click on add to cart the Csize remains 0.
How to fix this ?
2
Answers
actually you are trying to
console.log()
just after you update the state,and
setState()
function is asynchronous. This means you cannot see updated value of state inside the same function(where you updated the state), so if you want to see updated state ofCSize
justconsole.log
outside theuseEffect
.btw you can directly use length of your
Cart
state without usinguseEffect
hookWhere are you using
handleClick
function?