Hi there.
I am bulding a cart using state and provider. At the beginning I had something like this:
const addToCart = () => {
dispatch({
type: "ADD_TO_CART",
item: {
key: key,
id: id,
title: title,
description: description,
img: img,
price: price,
},
});
};
<Button
variant="default"
className="btnBgColor btnTextColor"
onClick={() => {
setKey(figure.key);
setId(figure.id);
setTitle(figure.title);
setDescription(figure.description);
setImg(figure.img);
setPrice(figure.price);
addToCart();
}}
>
It didn´t work properly. I was one step behind all the time: when adding the first item, empty object in basket array, when adding second item, first item in basket array, and so on.
I changed my approach and did something like this:
const addToCart = (key, id, title, description, img, price) => {
setKey(key);
setId(id);
setTitle(title);
setDescription(description);
setImg(img);
setPrice(price);
dispatch({
type: "ADD_TO_CART",
item: {
key: key,
id: id,
title: title,
description: description,
img: img,
price: price,
},
});
};
<Button
variant="default"
className="btnBgColor btnTextColor"
onClick={() => {
addToCart(
figure.key,
figure.id,
figure.title,
figure.description,
figure.img,
figure.price
);
}}
>
Now it works. And I don´t understand why. By passing parameters in my function, is updating the state inmediately? Without using async-await?
By the way, I tried to make it async but as soon as I wrote “await” my code editor was saying that it wouldn´t have effect.
Thanks.