0

I need to update an object nested in an array nested in an object, so far I have been successful with using useState with spread syntax:

playerState = {
        resources: {
            coins: 2,
            ...
        },
        availableAdventurers: 2,
        hand: [],
        activeCard: false,
        drawDeck: [],
        discardDeck: [],
        playedCards: [],
        destroyedCards: []
    };

This was updated without problems:

let tPlayerState = {...playerState};
...
tPlayersState.discardDeck.push(card);
...
setPlayerState(tPlayerState);

But it doesn't work in this case:

let tLocations = {...locations};
tLocations[locationLevel][locationIndex].state = LOCATION_STATE.occupied;
console.log("Target location state: " + tLocations[locationLevel][locationIndex].state);
console.log("Locations copy state:");
console.log(tLocations);

While the first log returns "occupied" as expected, when I check the whole object, I see that the state was not changed:

"Target location state: occupied"

"Locations copy state:
{…}
​I: (2) […]
  ​​0: Object { type: "brown location", exploreText: {…}, state: "explored", …" }

I would expect to see that the state is "occupied" in both cases as I am referencing the same object, but that is not the case - why?

Faire
  • 706
  • 1
  • 9
  • 31
  • You have nested objects, spread is just a *shallow* copy. – jonrsharpe Mar 09 '20 at 09:25
  • Does this answer your question? [Deep copy in ES6 using the spread syntax](https://stackoverflow.com/questions/38416020/deep-copy-in-es6-using-the-spread-syntax) – jonrsharpe Mar 09 '20 at 09:25
  • I thought it is connected with shallow copy, but why did it work wiith other nested objects? I have put one such example in the question. – Faire Mar 09 '20 at 09:51

0 Answers0