SvenJS 3

Store

createStore is a tiny pub/sub. It is not Redux.

import { createStore } from "svenjs";

const store = createStore({
  state: { posts: [] },
  init() {
    fetch("/api/posts")
      .then((r) => r.json())
      .then((posts) => this.set({ posts }));
  },
});

store.get();
store.set((s) => ({ ...s, posts: [] }));

A component that should re-render when the store changes calls this.observe(store) in onMount. That schedules a patch without touching component state, and unsubscribes on destroy.

const List = create({
  onMount() {
    this.observe(store);
  },
  render() {
    return html`<ul>${store.get().posts.map((p) => html`<li key=${p.id}>${p.title}</li>`)}</ul>`;
  },
});

Store set notifies subscribers synchronously. Component setState still batches into a microtask. If a listener throws, later listeners still receive the update and the first error is rethrown afterwards.

Nested set during a notification applies immediately for get(), then notifies every listener for each state in order. Nobody receives an older snapshot after a newer one.

listenTo is an alias for subscribe. emit(data) is an alias for set(data). Use subscribe yourself when the store update should derive local state, not just re-render.