I need to update state of my array order conditionally (checking for duplicates), but can't access order values inside function addToBasket.
At the same time it's updated and I have an access there in my first console.log (see the snippet below):
const [order, setOrder] = useState<IGoodsCart[]>([]);
console.log(order); **//1 visible**
const addToBasket: AddToBasketFunc = (item) => {
console.log(order); **//2 not visible**
const itemIndex = order.findIndex((orderItem) => orderItem.id === item.id);
if (itemIndex < 0) {
const newItem = {
...item,
quantity: 1,
};
setOrder((order) => [...order, newItem]);
} else {
const newOrder = order.map((orderItem, index) => {
if (index === itemIndex) {
return {
...orderItem,
quantity: orderItem.quantity + 1,
};
} else {
return orderItem;
}
});
setOrder(newOrder);
}
};
What's the best way to manage with it?
I was thinking to use useRef hook, but hope that there is another best solution for this case.