Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

redux react update array after copying array

I have a question I’m facing a problem that I can’t update array after copying it.
If I copy an array and don’t update the id, when I type something on input the text will appear in the same way where I copy it.

here is my Initialstate

const initialState = [
  {
    id: random numbers,
    options: [{ id: random numbers , value: '' },
    ],
  },
];

it will have a lot of option
and I just would like to update options id

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this is what i tried

    case COPY_QUESTION: {
      const newArray = [...state];
      const copyQuestion = newArray[action.payload];
        copyQuestion.options.map((option) =>
          Object.assign({}, option, {
            id: random number,
          }),
        );
      
      return [...state, copyQuestion];
    }

thanks for reading my question.

>Solution :

it’s caused due to call-by-reference.
As I can see in your code,
You are copying the reference of an array which might have the reason to overwrite details of the original array when you are typing. You can copy the values of the original array by using Javascript Object Prototype

so in that, you need to destruct your array or break your reference in the duplicate array.
example

let A = [a,b,c]  //original Array
let B =  JSON.parse(JSON.strigify(A))  // duplicate Array
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading