I've a map that the value of each key is also a map that for each key store some int or string as a value. I store the first map in a state and I also store a copy of the map in useRef for storing the previous state if I want to cancel all the changes I made for current state and go back to previous state.
I always make a deep copy of the maps in order that the changes I make in the state won't affect the previous state but when I change the current state, the previous state also change and I don't know where the problem is.
const [weightsValues,updateWeightsValues]=useState(new Map())
const oldState=useRef(new Map())
useEffect(()=>{
const weightsAndClassesTemp=new Map();
weightsAndClassesTemp.set("A",new Map())
weightsAndClassesTemp.set("B",new Map())
weightsAndClassesTemp.get("A").set("aa",0.65)
weightsAndClassesTemp.get("A").set("bb","c")
weightsAndClassesTemp.get("B").set("aa",0.9)
weightsAndClassesTemp.get("B").set("bb","a")
let response={data:{valueOfWeightAndClass:weightsAndClassesTemp}}
oldState.current=response.data.valueOfWeightAndClass
updateWeightsValues(response.data.valueOfWeightAndClass)
},[])
//function for changing single value
function onChange(value,className,weight){//change value
let newClassWeights=new Map(weightsValues)
newClassWeights.get(className).set(weight,value)
updateWeightsValues(newClassWeights)
}