I have a state in my component and i want to clone of this state when click the save button and change and remove some attribute of the clone and then post to back-end , but when i change the clone array the original state change too ; i don't know what to do i trace all of ways to clone array but all of them did not help me ; below is my codes :
.
.
.
const [steps , setSteps] = useState([
{
id: 1,
// content: "item 1 content",
subItems: [
{
id: 10,
isNew : false ,
hasWorkflow : true ,
title : 'SubItem 10 content' ,
approverType : 1,
approverId : 0 ,
},
{
id: 11,
isNew : false ,
hasWorkflow : true ,
title : 'SubItem 11 content' ,
approverType : 2,
approverId : 1 ,
}
]
},
{
id: 2,
// content: "item 2 content",
subItems: [
{
id: 20,
isNew : false ,
hasWorkflow : false ,
title : 'SubItem 20 content' ,
approverType : 2,
approverId : 4 ,
},
{
id: 21,
isNew : false ,
hasWorkflow : false ,
title : 'SubItem 21 content' ,
approverType : 1,
approverId : 3,
}
]
} ,
{
id: 3,
content: "item 3 content",
subItems: [
{
id: 55,
isNew : false ,
hasWorkflow : false ,
title : 'SubItem 20 content' ,
approverType : 2,
approverId : 6 ,
},
{
id: 66,
isNew : false ,
hasWorkflow : false ,
title : 'SubItem 21 content' ,
approverType : 2,
approverId : 4 ,
}
]
}
]);
.
.
.
.
function handleSaveWorkflow(){
//const _result = steps.slice(0);
let _result = [...steps];
_result.map((item , index) => {
item.subItems.map((i , ind) => {
delete i.hasWorkflow;
if(i.isNew){
i.id = null;
}
delete i.isNew;
return i;
});
return item;
});
const _final = {"steps" : [..._result]};
console.log('result : : : : : : :: : :: : ' , _final);
console.log('steps : : : : : : :: : :: : ' , steps);
// alert(_final);
workflowAxios.post(`/workflow-templates/${props.id}/workflow-template-steps` , '' , _final)
.then(response => {
console.log('response e e e e e e e : ' , response);
// setSteps(response);
})
.catch(error => {
console.log('error r r r r r r r r r : ' , error);
});
}
For deep copy try this
let _result = JSON.parse(JSON.stringify(steps));
or
const newArray = steps.map(step => ({...step}));
spread syntax doesn't give a deep copy
Deep copy
A deep copy means actually creating a new array and copying over the values, since whatever happens to it will never affect the origin one.
For more clarification and the better understanding, you can refer How do you clone an Array in Javascript?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With