SnippSync

Always Fresh Code

reactive-store.js

code-snippets
Lines 0-45
Auto-synced 25 days ago
This snippet automatically syncs with your GitHub repository
SnippSync
JS
reactive-store.js
1/**
2 * Creates a simple reactive store using a JS Proxy.
3 * @param {object} initialState - The initial state object.
4 * @param {function} onUpdate - The callback function to run on any state change.
5 * @returns {Proxy} A proxy-wrapped state object.
6 */
7function createReactiveStore(initialState, onUpdate) {
8  return new Proxy(initialState, {
9    set(target, property, value) {
10      // First, update the actual value in the target object
11      target[property] = value;
12
13      // Then, trigger the callback to notify of the change
14      console.log(`State updated: ${property} is now`, value);
15      onUpdate(target);
16
17      // Return true to indicate the assignment was successful
18      return true;
19    },
20  });
21}
22
23// --- Example Usage ---
24
25// Let's say we have an element to display our user's name
26// <h1 id="user-name"></h1>
27const userNameElement = document.getElementById("user-name");
28
29// A function to update our UI
30const render = (state) => {
31  if (userNameElement) {
32    userNameElement.textContent = state.name;
33  }
34};
35
36// Create our reactive store
37const userState = createReactiveStore({ name: "Alex" }, render);
38
39// Initially render the UI
40render(userState); // Renders "Alex"
41
42// Now, whenever we update the state, the UI updates automatically! ✨
43setTimeout(() => {
44  userState.name = "Jordan"; // Console logs the update and re-renders the h1 to "Jordan"
45}, 2000);
46

Powered by SnippSync • Always fresh, always in sync

Create Your Own Auto-Synced Snippets

Keep Your Documentation Always Fresh

Create snippets that automatically sync with your GitHub repositories. Never worry about outdated documentation again.

Auto-sync with GitHub
Beautiful embeds
Share anywhere