JSFiddle - React, Tailwind, and code Playground

by jsbot

JavaScript

const watch = ({
  target = window,
  propertyName,
  onChange,
  value = target[propertyName]
}) => {
  Object.defineProperty(target, propertyName, {
    get: () => {
      return value;
    },
    set: (newValue) => {
      if (newValue !== value) {
        value = newValue;
        onChange(value)
      }
    }
  })
}

const obj = {
  status: 1
}

watch({
  target: obj,
  propertyName: 'status',
  onChange: value => {
    console.log('updated:', value)
  }
})
console.log('status1:', obj.status)
obj.status = 10;
obj.status = 10;
obj.status = 20;
console.log('status2:', obj.status)