'Cloning large data structure ReactJS makes value go missing
Hullo there, I have an array which each value has a deep Tree object. I'm keeping a version of this in a useState hook and another in a useRef. My idea is to make the changes on the ref and therefore update the state. My problems started on keeping the array ordered, so I added an order key to sort it.
This is a wrapper function to update the state, it isn't sorting nor cloning (either shallow or deep) the array makes the last value disappear
const updateScope = (newScopes = null as ScopesProps[]) => {
if (newScopes) {
scopesRef.current = newScopes;
}
const supposedToBeSorted = scopesRef.current.sort(
(a, b) => a.order - b.order
);
console.log("aha, gotcha", supposedToBeSorted, [...supposedToBeSorted]);
setScopes([...supposedToBeSorted]);
};
And this is what I got logged
aha, gotcha
[{…}]
0: {id: 110134, main: {…}, loaded: false, reorderCriteria: '', order: 1}
1: {id: 107950, main: {…}, loaded: false, reorderCriteria: '', order: 0}
length: 2
[[Prototype]]: Array(0)
[{…}]
0: {id: 110134, main: {…}, loaded: false, reorderCriteria: '', order: 1}
length: 1
[[Prototype]]: Array(0)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
