I'm having issues with cloning arrays in my react application.
I import an array with data to my app called ApplicationsData. It's an array of objects.
import ApplicationsData from '../Store/Applications';
App component has the following state:
constructor(props) {
super(props);
this.state = {
isOn: true,
untouchedApplications: [...ApplicationsData],
applications: [...ApplicationsData],
activeWindows: [...defaultActive],
background: "#3a6ea5"
};
}
I make a clone of the array with data using the "..." spread operator.
In my context I have a method - openApp - Which changes a property in an element in state.applications.
openApp: (appID) => {
let appIndex = this.state.applications.findIndex( el => el.id == appID);
let clone = [...ApplicationsData];
clone[appIndex].isActive = true;
clone[appIndex].newProp = true;
clone[appIndex].isMinimized = false;
this.setState({applications: clone})
},
Whenever I get to the clone[appIndex].prop = value
both state.applications and untouchedApplications gets overridden with that data, despite having used spread operators both in state and in openApp. The untouchedApplications array in state is not used anywhere in the app or the method but also gets updated. Also the newProp property being assigned to the cloned array is not present in the original array with data but does get applied to both arrays in the state after adding it to the cloned array.
I have also tried using Array.from
and state.applications.slice()
to create clones. I'm feeling a bit lost here, since I was sure this was the correct way of cloning arrays.
I'm sorry for messy code indentation. I have no clue how to make SO format it properly. Either first line is way before other lines or all lines start 8 tabs in. Any tips on that are appreciated as well.