JavaScript Proxy сильно выручает, когда нужно ловить обновления стейта.
// Building a reactive store with Proxy
const createReactiveStore = (data, onChange) => {
return new Proxy(data, {
set(target, key, value) {
const oldValue = target[key];
target[key] = value;
onChange(key, value, oldValue);
return true;
},
});
};
// Usage
const state = createReactiveStore(
{ count: 0, status: 'idle', isOnline: false },
(key, newVal, oldVal) => {
console.log(`🔁 ${key}: ${oldVal} -> ${newVal}`);
// You can handle business logic or UI updates here
}
);
state.count = 5; // 🔁 count: 0 -> 5
state.status = 'loading'; // 🔁 status: idle -> loading
state.isOnline = true; // 🔁 isOnline: false -> true
state.status = 'error'; // 🔁 status: loading -> error
state.count++; // 🔁 count: 5 -> 6
@WebDev_Plus