Today I Learned - Rocky Kev

TIL using proxies for reactivity

POSTED ON:

TAGS:

What is a JavaScript Proxy?
A Proxy let you detect when someone gets, sets, or updates a property on an object, and run code when they do.

Here's how it looks.

const target = {
name: 'John Doe',
age: 30
};

const handler = {
get: function(target, property) {
if (property === 'age') {
return target[property] + 5; // Adds 5 to the age property
} else {
return target[property];
}
}
};

const proxy = new Proxy(target, handler);

console.log(target.name); // Output: "John Doe"
console.log(target.age); // Output: 30
console.log(proxy.name); // Output: "John Doe"
console.log(proxy.age); // Output: 35

Looks neat. But why not just pass the value like this?

const newTarget = { ...target };
newTarget.age = newTarget.age + 5

So really -- why would you use it?

That's why I really like this post: How vanilla JS Proxies work

var wizards = {
neville: 'Gryffindor',
malfoy: 'Slitherin',
cedric: 'Hufflepuff'
};

var handler = {
get: function(obj, prop) {

// Hiss for Slitherin
if (obj[prop] === 'Slitherin') {
return 'Hisssssss....';
}

// Return the value
// This is what happens by default when you don't have a Proxy
return obj[prop];

},
set: function(obj, prop, value) {

// Save our wizards to localStorage
localStorage.setItem('wizardsAndSuch', JSON.stringify(obj));

// Set a property
// This is what happens by default when you don't have a Proxy
obj[prop] = value;

// Indicate success
return true;

},
deleteProperty: function (obj, prop) {

// Delete the property
delete obj[prop];

// Indicate success
return true;

}
};


var wizardsProxy= new Proxy(wizards, handler);

So what's the magic here?

When you add/update the object, it also updates localStorage!


Related TILs

Tagged:

TIL using proxies for reactivity

A Proxy let you detect when someone gets, sets, or updates a property on an object, and run code when they do. But why? This usecase -- when you add/update the object, it also updates localStorage!

TIL using proxies for reactivity

A Proxy let you detect when someone gets, sets, or updates a property on an object, and run code when they do. But why? This usecase -- when you add/update the object, it also updates localStorage!

TIL using proxies for reactivity

A Proxy let you detect when someone gets, sets, or updates a property on an object, and run code when they do. But why? This usecase -- when you add/update the object, it also updates localStorage!