A small reactive store
Change state like a normal object, and every subscriber is told. The idea behind many UI libraries.
JavaScript · A small reactive storeAdvanced
function createStore(initial) {
const subscribers = new Set();
const state = new Proxy({ ...initial }, {
set(obj, key, value) {
const old = obj[key];
obj[key] = value;
if (old !== value) subscribers.forEach((fn) => fn(key, value, old));
return true;
},
});
return { state, subscribe: (fn) => (subscribers.add(fn), () => subscribers.delete(fn)) };
}
const { state, subscribe } = createStore({ count: 0, user: null });
const log = [];
subscribe((key, value) => log.push(key + '=' + value));
state.count++;
state.count++;
state.user = 'Ali';storestateproxysubscribe