Kohl Byrd
Kohl Byrd

Reputation: 3

How can I see if my object updates in a loop?

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)
    }
})();

Upvotes: 0

Views: 41

Answers (2)

T. Jami
T. Jami

Reputation: 1016

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

Upvotes: 0

Guerric P
Guerric P

Reputation: 31815

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 };

Upvotes: 1

Related Questions