0

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

AbsoluteBeginner
  • 2,160
  • 3
  • 11
  • 21
Nasir
  • 233
  • 2
  • 12
  • `s` or `item` (in the `.map()` calls) are not a copies of an element, but the element itself. If you change it, the original element changes. – tevemadar Jul 25 '21 at 09:19
  • 1
    `[...state]` and `map` only create a shallow copy of the `state` array, ie, the elements in the new array are just references to the elements in the original array. – derpirscher Jul 25 '21 at 09:20
  • It's a really bad idea to mutate an array as you iterate over it. The map method can transform the elements by return the new version of each element. – dwjohnston Jul 25 '21 at 09:20
  • const onSubmit = () => { const data = state.map(item => { const copliedItem = JSON.parse(JSON.stringify(item)); copliedItem.value = item.value === true ? 'Bypass' : 'Normal'; return copliedItem; }); document.getElementById('jsonData').textContent = JSON.stringify(data, null, 2); }; I replaced my code with this. now its working fine – Nasir Jul 26 '21 at 05:56

1 Answers1

0

the map function will always return a new array with elements that are the result of a callback function.

In your case, the map function should return a new array with the value changed to Bypass or Normal and it will be stored in the constant data. However, you can still access your original array by calling oldData