I'm creating a sneaker store where I have an add to cart function,
first, when the add to cart is clicked it updates the size that's selected second it adds the changed item,
object into the cart State the problem is that on the first click there is no object returned but
every time after the first click it returns the data.
this is the function that updates the size:
const updateSelectedSize=(item,selectedSize)=>{
item.size=selectedSize;
return item;
}
here is the function that I use to add the updated item to the cart:
const handleAddtoCart=(item,selectedSize)=>{
const updatedItem=updateSelectedSize(item,selectedSize);
let newitemArray=[...cart,updatedItem]
setcart(newitemArray)
console.log(cart);
}
here is the component that executes the function on click:
<i onClick={()=>{handleAddtoCart(product,selectedSize)}}className="fa-solid fa-cart-arrow-down"></i>
here is the console.log of the first click:

and here's the console log of the second click:

as you can see nothing happens on the first click I'm thinking this is has something to do with the useState cart variable and the spread operator the initial value for it is:
const [cart, setcart] = useState('');
I've tried to set the value to different things such as an empty array but it always gives the same result.
Because you write your console.log(cart) inside the handleAddtoCart and your state not updated yet.
if you move console.log(card) outside of handleAddtoCart function, you can see the result is work perfectly.
And for empty array it is better to use
✅ const [cart, setcart] = useState([]);
instead of this one
❌ const [cart, setcart] = useState("");
Full code is here
export default function App() {
const [cart, setcart] = useState([]);
const updateSelectedSize = (item, selectedSize) => {
item.size = selectedSize;
return item;
};
const handleAddtoCart = (item, selectedSize) => {
const updatedItem = updateSelectedSize(item, selectedSize);
let newitemArray = [...cart, updatedItem];
setcart(newitemArray);
console.log("STATE NOT UPDATED YET", cart);
};
console.log("STATE UPDATED", cart);
return (
<div className="App">
<i onClick={() => { handleAddtoCart({ size: 3 }, 2) }}>
CLICK TO SET
</i>
</div>
);
}
Best.