skip to Main Content
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


  1. 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 of CSize just console.log outside the useEffect.

    btw you can directly use length of your Cart state without using useEffect hook

    <Link to="/Cart" className="bikescart"><ShoppingCart color="#ffffff" size={35}/>
    <span>{Cart.length}</span>
    </Link>
    
    Login or Signup to reply.
  2. Where are you using handleClick function?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search