0

I want this code to check if one of the keys in the "states" object updates from false to true, and if it does, then run the code inside of the if-statement. For some reason, even if I update the states variable manually (like I did here). The code never runs.

I'm using the "compareMe" variable to hold the last version of the "states" object by setting it equal to the "states" object at the end of the loop.

I'm sure this is not the best approach, any ideas would help a ton.

function sleep(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms * 1000)
    })
}

var states = { Dad: false, Mom: false, Brother: false, Sister: true }
var compareMe = {}
var loop = 0;

(async () => {
    while(true) {
        loop++
        if (loop === 5) {
            states.Dad = true
        }
        for (const key of Object.keys(states)) {
            if(compareMe[key] === false && states[key] === true) {
                console.log("Opening Door")
            } else {
                console.log('No change')
            }   
        }
        compareMe = states;
        await sleep(5)
    }
})();
Kohl Byrd
  • 3
  • 1
  • so you want to watch a variable if it gets updated and if it does then a function should be called, right? – MrJami Aug 16 '21 at 21:56
  • @MrJami Yes, if one of the values in the states object changes from false to true, I want to run a function – Kohl Byrd Aug 16 '21 at 22:00

2 Answers2

1

What you are doing with compareMe = states is create a new reference on the same object, so whenever you mutate states, the mutation reflects on compareMe.

You should perform a clone instead:

compareMe = { ...states };
Guerric P
  • 30,447
  • 6
  • 48
  • 86
0

You can use proxy object to monitor your object for changes.

original answer with more details

var targetObj = {};
var targetProxy = new Proxy(targetObj, {
  set: function (target, key, value) {
      // function called
      console.log(`${key} set to ${value}`);
      target[key] = value;
      return true;
  }
});

targetProxy.newProp = "test"; // console: 'newProp set to test'

However it would be easier for you to just use a library to monitor and watch variables. There are many libraries and frameworks to do this. Library: Obseravble-Slim Framework: Angular

MrJami
  • 685
  • 4
  • 16