Is there any way to directly change the value of the target of a Proxy in js?

Viewed 19

I did some research on Js Proxy and ran a small test.

My aim is to run a function called render whenever a user changes the value of a variable.

Here is my code:

const render = (data) => {
  console.log(`I rendered with value: ${data}`)
}

const reactive = (data) => {
  const target = {
    value: data
  }

  const handler = {
    set(target, prop, receiver) {
      render(receiver);
      return Reflect.set(...arguments);
    }
  }

  const proxy = new Proxy(target, handler)
  
  return proxy;
}

// testing

let magicA = reactive('hello');

console.log(magicA.value)

magicA.value = 'bye'

console.log(magicA.value)

It works normally, but I have to get or set its value via the value property!

I want to get or set directly via the variable itself. That means

let magicA = reactive('hello');

console.log(magicA)

magicA= 'bye'

console.log(magicA)

but still get the same result as before.

0 Answers
Related