I’m working on this task where I need to do the following:
I have this object passed by reference from 4 components
const InitialStateSubjects = {
"1":{
"name": "math",
"selected": true}
"2":{
"name": "English",
"selected": true}
}
const Subjects = {
"1":{
"name": "math",
"selected": false}
"2":{
"name": "English",
"selected": true}
}
const [initialState, setInitialState] = useState(subjectsObj)
const [changedState, setChangedState] = useState(subjectsObj)
//this is the way I'm filtering but it's not working because it's comparing two identical objects
const changedSubjects = Object.keys(changedState)
.filter(key => initialState[key]?.selected !== changedState[key]?.selected
.map(key => console.log(initialState[key]?.name))
As you can see they both need to have the same object passed which is subjectObj
Most of the logic is done with the changedState, and I only set the initial one once in the useEffect, but regardless, both the initialState
& changedState
gets changed at the same time. I want to use the initial value of Initial state to compare the difference and return the name of the subjects that selected
values changed. I have tried doing in this in the console and it works brilliantly but when doing in React I am stuck with this. I have tried spread operator to make a shallow copy of it, and used a library to make a deep clone of it but it still mutates the initial object. If you do think of a different way to compare initial state without creating another state that would also work for me because all I want is to return the ones that changed upon clicking a button from their original initial state. Thanks so much in advance!