When adding an item to the cart and doing some calculations, I output the result, the first click shows the local array but the useState array doesn't appear until add the next item and seems to be always one pace behind.
useEffect(() => {
// Calculates the amount of one item in the cart for each item
let c;
let arr = [];
items.forEach(x => {
c = 0
items.forEach(y => {
if (x.id === y.id) {
c++
}
});
arr.push({ id: x.id, title: x.title, price: (x.price * c), amount: c })
});
let uniqueItems = arr.reduce((acc, item) => {
if (!(item.id in acc)) {
acc[item.id] = item;
}
return acc;
}, {});
setItemsCount(uniqueItems)
console.log(uniqueItems)
console.log(itemsCount)
// Calculates the total cost of each product
// Could be done in the above code making this redundent.
const sumWithInitial = items.reduce((accumulator, object) => {
return accumulator + object.price;
}, 0);
setTotal(sumWithInitial);
}, [items]);
@MohamedTammam This isn't the problem, when clicking an button, the useEffect is run because the cart has been updated, uniqueItems displays the items, on that click, but itemsCountsetItemsCount(uniqueItems) doesn't display until the button is pressed again.
I tried what you suggested but it has the same outcome.
omg. Sorry, I just console logged it in the return of the component and everything is working as should.
But now I have another problem, in that the useState doesn't want map through. Its displaying the error of Uncaught TypeError: itemsCount.map is not a function.
@Randy_Johnson only if you are not consistent with what a variable holds :) if you assume a variable is an array, it must always be an array
If you change it to null, undefined, a string, an integer or an object, it will fail. Based on the name I would assume it's an integer
@Sinnbeck Yes, sorry my names are a little miss leading. Originally it was an array.
const items = {id: 1, name: 'apple', price: 2.99}
but something happened here:
let uniqueItems = arr.reduce((acc, item) => {
if (!(item.id in acc)) {
acc[item.id] = item;
}
return acc;
}, {});
But am so new to JS that the facts that its progression was good enough. But here am guessing its turning it into an Object. And I turn it back using const propertyValues = Object.values(uniqueItems)