Reputation: 1681
I have read a few answers regarding my question but I am still not sure how to fix this issue. I have a tree object that is moderately nested. When updating the values in the tree I am well aware of the rules not to update the state directly, so I create a shallow copy of the tree, make the modifications and update the state for the tree to be properly displayed. I noticed something odd; however. When I update the shallow copy of the tree, the state gets updated.....I am not sure how or why, but I am sure it's a concept I am not understanding. Would love some help getting around this if it IS an issue:
export const FldDataTree = (props) => {
const [treeData, setTreeData] = useState({data:[]})
const findNode = (node,id) => {
let result;
for(let i=0;i<node.length;i++){
if(node[i].recordid == id) return(node[i]);
if(node[i].children){
result=findNode(node[i].children,id);
}
return result;
}
}
const HandleFormCallback = (resp) => {
if(resp.action=="save"){
if(controls.editid){
let ns = treeData.data;
let node = findNode(ns,controls.editid)
if(node){
node.foldername = resp.data.foldername
console.log(treeData.data) //<=============treeData.data was updated....why?
}
}
}
}
Upvotes: 1
Views: 52
Reputation: 66
In your case, the shallow copy won't work, as it's a tree structure the nested objects won't get cloned.
To do a deep copy you can use let ns = JSON.parse(JSON.stringify(treeData.data))
or any third party library for deep copy.
Upvotes: 2