I have a react state variable, I wanted to check if something changes out there then my useEffect() hook can sense that and show me the submit button visible. So for that I had the original const variable as it is, and I made the state copy of the same variable using useState().
Eg:
const abc = {MONDAY:{OperatingHours: ["00:00", "23:59"], toggle: false}, TUESDAY:...};
const[stateAbc, setStateAbc] = useState(MONDAY:{OperatingHours: ["00:00", "23:59"], toggle: false}, TUESDAY:...});
I wanted to compare the these two variable in my React component. If showButton is set as false I won't make the button visible else I will make it.
When I am making the state variable changes (like OperatingHours) back to initial states ["00:00", "23:59"] while running my application, I can't enter into this condition (abc === stateAbc) and the submit button is still visible:
const initialRender = useRef(true);
useEffect(() => {
if (initialRender.current) {
initialRender.current = false;
}
if (abc === stateAbc) {
setSubmitButtonDisabled(true); // This condition is never meeting
}
if (abc !== stateAbc) {
setSubmitButtonDisabled(false);
}
}, [stateAbc]);
CodePudding user response:
if we have two objects Obj_1 and Obj_2
in JavaScript when comparing two objects the condition Obj_1 === Obj_2 will compare the reference for the Obj_1 object with the reference for the Obj_2 object ... this means even if the two objects contain the same properties inside them .. the comparison will always return false!
from a quick search in google for "how to compare two objects" .. the first answer I found is to stringify the objects first before making the comparison .. which means convert the objects and its properties to a string and then make a comparison between strings :)
JSON.stringify(Obj_1) === JSON.stringify(Obj_2)
and your condition should be like this:
if (JSON.stringify(abc) === JSON.stringify(stateAbc)) {
setSubmitButtonDisabled(true);
}
CodePudding user response:
Comparing objects with ===
only gives true if the objects are the same :
const a = { name: "John Doe" };
const b = a;
console.log(a === b); // true
----
const a = { name: "John Doe" };
const b = { name: "John Doe" };
console.log(a === b); // false
Sometimes you see developers use JSON.stringify(a) === JSON.stringify(b)
but it's not safe at all, the object properties are not always in the same order:
const a = { name: "John Doe", age: 30 };
const b = { age: 30, name: "John Doe" };
console.log(a, b) // { name: "John Doe", age: 30 } { age: 30, name: "John Doe" }
If you have simple objects to compare (all the values are primitive values), you can compare them by iterating through the properties :
let equals = true;
for (let key of a){
if (a[key] !== b[key]) equals = false;
}
But if you have nested objects which is your case, the best way is to use an npm package for the comparison such as deep-equal.