So i feel like an idiot. Im getting numbers strung together instead of added from my state. I cant seem to solve it using normal update state methods. Its for component that selects how many of an item to buy from an invintory. Everything worked when i had on the option to buy one at a time. Now i have added the 'puchaseAmount' state that should control it. and the quantity breaks and strings '010101010' if i try to buy 10 at a time. The same thing happens to the total items owned count. I feel im missing something simple and stupid lol
const [quantityOwned, setQuantityOwned] = useState(0);
const [purchaseAmount, setPurchaseAmount] = useState(10);
const productIndex = newArray.findIndex((p) => p.id === product.id);
if (productIndex !== -1) {
newArray[productIndex].quantity = newArray[productIndex].quantity + purchaseAmount
const newCost = newArray[productIndex].cost * increaseConstant;
newArray.push({
...product,
cost: newCost
});
} else {
newArray.push({
...product,
quantity: purchaseAmount,
});
}
if (productType === 'items') {
setPlayerCharacter({
...playerCharacter,
items: newArray,
});
}
// // Increase product cost
const newCost = product.cost * 1.1;
product.cost = newCost.toFixed(2);
// PPC Product
if (product.type === 'pointsPerClick') {
// Assign current values
let currentPointsPerClick = playerCharacter.pointsPerClick;
let currentTotalScore = playerCharacter.totalScore;
let newPointsPerClickValue = currentPointsPerClick + product.effect;
let newTotalScore = currentTotalScore - product.cost;
setQuantityOwned(quantityOwned + purchaseAmount); // This is the trouble
// i tried also (prev => prev + purchaseAmount)
let newTotalBuildingsOwned = playerCharacter.totalBuildingsOwned;
let newTotalItemsOwned = playerCharacter.totalItemsOwned;
if (productType === 'items') {
const newNum = playerCharacter.totalItemsOwned + purchaseAmount;
newTotalItemsOwned = newNum;
}
if (productType === 'buildings') {
const newNum =
playerCharacter.newTotalBuildingsOwned + purchaseAmount;
newTotalBuildingsOwned = newNum;
}
setPlayerCharacter({
...playerCharacter,
pointsPerClick: newPointsPerClickValue,
totalScore: newTotalScore,
totalItemsOwned: newTotalItemsOwned,
totalBuildingsOwned: newTotalBuildingsOwned,
});
}