Skip to content

Instantly share code, notes, and snippets.

@helabenkhalfallah
Last active May 20, 2024 18:24
Show Gist options
  • Save helabenkhalfallah/b0fbcd2b842e9a06ad2fc0562049cf89 to your computer and use it in GitHub Desktop.
Save helabenkhalfallah/b0fbcd2b842e9a06ad2fc0562049cf89 to your computer and use it in GitHub Desktop.
Reactive Store
// Function to create a reactive store
function createStore(initialState) {
// Store the initial state in a private variable
let state = initialState;
// Array to hold subscribers (callbacks)
const subscribers = [];
// Create a proxy for the state object
const stateProxy = new Proxy(state, {
// Trap for setting a property value
set: function(target, property, value, receiver) {
// Update the value of the property
Reflect.set(target, property, value, receiver);
// Trigger callbacks (subscribers) with the updated state
subscribers.forEach((callback) => callback(stateProxy));
// Indicate success
return true;
},
});
// Function to get the current state
function getState() {
return stateProxy;
}
// Function to subscribe to state changes
function subscribe(callback) {
subscribers.push(callback);
// Return a function to unsubscribe
return function unsubscribe() {
const index = subscribers.indexOf(callback);
if (index !== -1) {
subscribers.splice(index, 1);
}
};
}
// Return the getter, setter, and subscribe functions
return {
getState,
subscribe,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment