Public
Edited
Apr 19
Insert cell
Insert cell
mutable logged = []
Insert cell
// Rerun this cell to observe
actions = {
store.dispatch({
type: "increment"
}); // log { count: 1 }
store.dispatch({
type: "increment"
}); // log { count: 2 }
store.dispatch({
type: "decrement"
}); // log { count: 1 }
return store
}
Insert cell
Insert cell
// Force update mutable with latest state

logger = ((event) => mutable logged = mutable logged.concat(store.getState()))
Insert cell
store = createStore({
reducer: (state, action) => {
switch (action.type) {
case "increment":
return {
...state,
count: state.count + 1
};
case "decrement":
return {
...state,
count: state.count - 1
};
default:
return state;
}
},
initialState: {
count: 0
}
})
Insert cell
createStore = ({ reducer, initialState }) => {
let state = initialState;

const { notify, ...subscribable } = createSubscribable();

const dispatch = createEventLoop({ reducer, state });

return {
...subscribable,
getState() {
return structuredClone(state);
},
dispatch(action) {
state = dispatch(action);
notify();
}
};
}
Insert cell
// magic happens here

function* EventLoop({ reducer, state }) {
while (true) {
/* action becomes reduced state
yielded on next iteration */
const action = yield state;
state = reducer(state, action);
}
}
Insert cell
createEventLoop = ({ reducer, state }) => {
const eventLoop = EventLoop({ reducer, state });
eventLoop.next();
return (action) => eventLoop.next(action).value;
}
Insert cell
createSubscribable = () => {
const eventName = "state-changed";
const eventTarget = new EventTarget();

const notify = () => eventTarget.dispatchEvent(new CustomEvent(eventName));
const subscribe = (listener) => {
eventTarget.addEventListener(eventName, listener);
return () => unsubscribe(listener);
};
const unsubscribe = (listener) =>
eventTarget.removeEventListener(eventName, listener);

return {
unsubscribe,
subscribe,
notify
};
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more