Blog>
Snippets

On-Demand Property Loading with Proxy

Create an example where a Proxy lazy-loads object properties on demand from a data source when they are first accessed.
// A function to simulate fetching data
const fetchData = key => {
  console.log(`Fetching data for ${key}...`);
  return `Data for ${key}`; // Simulated data
};

// The target object with the initial data
const initialData = {
  id: 1,
  name: 'John Doe'
};

// The Proxy handler with get trap to handle on-demand loading
const handler = {
  get: (target, property) => {
    if (!(property in target)) {
      // Lazy-load the property if it's not already present
      target[property] = fetchData(property);
    }
    return target[property];
  }
};

// The Proxy that wraps the target object
const proxy = new Proxy(initialData, handler);

// Usage example
console.log(proxy.email); // Will fetch the data on first access
console.log(proxy.email); // Subsequent access won't trigger fetching
This Javascript code example demonstrates on-demand property loading using a Proxy. When a property is first accessed, the Proxy's 'get' trap checks if the property exists on the target object. If not, it simulates fetching the data through the 'fetchData' function and stores it in the target object. This lazy-loading approach ensures that data is only retrieved when necessary, reducing unnecessary data fetching. The initialData object contains predefined properties, and the usage example at the end demonstrates accessing a property which triggers the lazy-loading mechanism.