I'm using react and trying to edit objects when a button is pressed. Currently, I have rendered 2 buttons on the page that display their correct values, but when the button is pressed I get "buttonUpgrades.map is not a function". The changeButtonData function can log the correct data but I cant seem to make any changes to the data.
From my understanding the reason this is sending an error is that buttonUpgrades is an object, but I don't know how to solve the issue.
import React, { useState } from "react";
const UpgradeButton = () => {
const [buttonUpgrades, updateButtonUpgrades] = useState([
{
id:0,
name: "Upgrade one",
cost: 5,
amount: 0,
damage: 1,
damageGrowth: 1.1,
},
{
id:1,
name: "Upgrade two",
cost: 6,
amount: 0,
damage: 2,
damageGrowth: 1.2,
},
]);
const changeButtonData = (data) => {
let {name,cost,damage} = data;
updateButtonUpgrades(...buttonUpgrades, name="new name") // this wont let me change the value that has been assigned
console.log(name) // this logs the name assigned to the button
}
return(
buttonUpgrades.map((upgrade)=>
<button key={upgrade.id}onClick={()=>changeButtonData(upgrade)}>
<h1>Cost:{upgrade.name}</h1>
<h1>Cost:{upgrade.cost}</h1>
<h1>Damage:{upgrade.damage}</h1>
</button>
)
)
}
export default UpgradeButton;
Edit: Solution incase anyone comes across this:
const changeButtonData = (data)=>{
const {id,name,cost,amount,damage,damageGrowth} = data;
updateButtonUpgrades(buttonUpgrades.map(buttonProps=>(buttonProps.id===id ? {...buttonProps,damage:damage * damageGrowth}:buttonProps)))
}