Sorry about the confusing title, I really didn't know what the categorize this as. I was having an issue regarding changing a variable that was set to an Array element. I have since figured out a way to accomplish what I wanted, but this was still bugging me so I figured I'd ask here.
playCard(event){
let tempArray = this.state.playerDeck;
let playArray = this.state.playerDefaultCards;
playArray.push(tempArray[event.target.id]);
console.log(playArray[1].image); //logs image data
let tempObject = tempArray[event.target.id];
tempObject.image = "Test";
console.log(playArray[1].image); //logs "Test"
tempArray[event.target.id] = tempObject;
this.setState ({playerDeck: tempArray, playerDefaultCards: playArray});
console.log(this.state.playerDefaultCards[1].image); //Also logs "Test"
}
Basically I have 2 arrays of objects with image sources. When an image is clicked on, I wanted it to go from the playerDeck to the playerDefaultCards, and then I just wanted to change the image source in the playerDeck to a blank string.
I thought that if I made a temporary variable and set it equal to the array element, changed that temporary variables image property and then set the array element equal to that new object everything would work out.
However when I change tempObject.image = "Test" it changes in both the tempArray and the playArray, which to my knowledge shouldn't happen. This is the source of my confusion.
Obviously I'm missing something but so far I haven't been able to figure it out.
tempArrayequal tothis.state.playerDeckyou are not making a copy of this variable. When you push items intotempArrayyou are still mutatingthis.state.playerDeck. If you want to make copies of these arrays you'd need to do something likelet tempArray = this.state.playerDeck.slice();... although I can't say I'd recommend doing this with React state.