Hi guys I am trying to create a board game using React and function components so I use hooks.
I've got an array of around 30 objects representing fields of the board:
[...,{
"id": 3,
"name": "Berlin",
"country": "Germany",
"price": 2500,
"floorPrice": 500,
"buildingPrice": 1500,
"baseFee": 300,
"maxFee": 2000,
"pawns": [],
"type": "city",
"owner": {}
},
{
"id": 4,
"name": "Warsaw",
"country": "Poland",
"price": 2400,
"floorPrice": 400,
"buildingPrice": 1200,
"baseFee": 250,
"maxFee": 1800,
"pawns": [],
"type": "city",
"owner": {}
},...]
When pawn steps on a specific field it can buy a property from this field just like in monopoly, by adding pawn as an owner in object. It works but when I try to buy another property/field then the last property I bought before this one lost it's owner.
This is my code for modifying copy of my array from json:
setAllFields(
allFields.map(item => (
{...item, owner: (item.id !== playerOne.position ? item.owner : (item.owner = {'owner': 'playerOne'}))}
))
);
I Would really appreciate any sugestions :)
let allFields = [];
const myFieldsArr = [
{
"id": 1,
"name": "Wroclaw",
"pawns": ['playerOne'],
"owner": []
},
{
"id": 2,
"name": "Warsaw",
"pawns": ['playerTwo'],
"owner": []
},
{
"id": 3,
"name": "Lodz",
"pawns": [],
"owner": []
}
]
allFields = myFieldsArr.map(field => (
{...field, owner: (field.id === 1 ? (field.owner =['playerOne']) : field.owner)}
))
console.log(allFields)
allFields = myFieldsArr.map(field => (
{...field, owner: (field.id === 2 ? (field.owner =['playerTwo']) : field.owner)}
))
console.log(allFields)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
"owner": ['playerOne']item.owner = {'owner': 'playerOne'}in the false case of the conditional? That's modifying a state object, which you seem to know you're not supposed to do.setPlayerTwo(existingValues => ({...existingValues, portfolio: [...playerTwo.portfolio, {'purchase': playerTwo.position}]}))