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
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.
CodePudding user response:
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