Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set Trap execute for two times – JS Proxy

Im working with proxies in js, but something is weird =>

let _usernames = [];

_usernames = new Proxy(_usernames, {
  set(target, prop, val) {
    console.count(); //this execute for two times!
    if(typeof val === 'string') {
      target[prop] = val;
      return true;
    } else {
      return false;
    }
  }
});

_usernames.push('Manuel');

The Set trap should call only once when i push to the array, but it executed twice.

And there is an error in the console, when i push to array =>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Uncaught TypeError: proxy set handler returned false for property '"length"'

How can i fix this and what’s wrong?

>Solution :

Calling Array#push causes set to be called two times:

  1. target=[], prop=0, val=Manuel: Adds a new value to an index
  2. target=["Manuel"], prop=length, val=1: Updates length of array

In your case, the second call is returning false since the length value is numeric.

A possible solution:

let _usernames = [];

_usernames = new Proxy(_usernames, {
  set(target, prop, val) {
    console.log(target, prop, val);
    if(typeof val === 'string' || prop === 'length') {
      target[prop] = val;
      return true;
    } else {
      return false;
    }
  }
});

_usernames.push('Manuel');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading