user1088793
user1088793

Reputation: 653

Is there a simple way in Javascript to run a function when a specific object property changes?

I am using a third party library that gives me a reference to its object when it initialises:

const flktyInit = (ref) => {
    flkty = ref.flkty;

    console.log(ref.state.flickityReady) //returns false on page load, but few seconds later returns true 
  };

What I am trying to make sure of is before I run a method from flkty, ref.state.flickityReady is true first. I have achieved this in a hacky form with setInterval, but this feels too hacky and can't find an obvious answer.

FYI this app is in a React environment.

Can anyone offer up a suggestion?

Upvotes: 2

Views: 43

Answers (1)

SomoKRoceS
SomoKRoceS

Reputation: 3063

In case you want to use vanilla javascript you'll have to use setInterval.

Since you've mentioned that you are using ReactJS, and as long as this behavior related to a component, I would recommend handling it as the component state, so when the state changes (and turning from false to true), you can execute a function call using useEffect (inside that useEffect you will have to check if the value is true or false before calling the function you want, But it will trigger useEffect each time the state of the component was updated.

Upvotes: 1

Related Questions