I have an array like :
export const switches = [
{ id: 1, switchName: 'HS - 3015', operation: 'Auto Start GA-3001 S', isActive: true },
{ id: 2, switchName: 'HS - 3016', operation: 'FSLL - 3001 (Pass - 1)', isActive: false },
{ id: 3, switchName: 'HS - 3017', operation: 'FSLL - 3002 (Pass - 2)', isActive: true }
];
In my component I added a additional property value
which is boolean and which is used for control switch.
In a function I first duplicate this array and than modify this duplicate array that is value: true/false
to value: 'normal/bypass'
. The big issue is I am not getting my original array. I am always get the modified array.
What is the problem, I can't figure out.
Switch change and Submit function like this:
const onSwitchChange = (e, switchId) => {
const { checked } = e.target;
const oldState = [...state];
const updatedState = oldState.map(s => {
if (s.id === switchId) {
s['value'] = checked;
}
return s;
});
setState(updatedState);
};
const onSubmit = () => {
const oldData = [...state];
const data = oldData.map(item => {
item.value = item.value === true ? 'Bypass' : 'Normal';
return item;
});
document.getElementById('jsonData').textContent = JSON.stringify(data, null, 2);
};
Find in codesandbox: https://codesandbox.io/s/switch-control-4ovyk