Concepts
Store Middleware
CapsuleStore gives you cross-capsule state with reducer actions, subscriptions, middleware, and devtools snapshots.
The minimum
Create a store with a reducer and initial state, subscribe with connect(), and update it with send().
import { CapsuleStore } from "tiny-engine-core";
export const cart = new CapsuleStore(
(state, action) => {
switch (action.type) {
case "add":
return {
items: [...state.items, action.payload],
total: state.total + action.payload.price,
};
default:
return state;
}
},
{ items: [], total: 0 }
);
cart.connect((state, action) => {
console.log("cart changed", action.type, state);
});
cart.send({ type: "add", payload: { id: 1, price: 10 } });Reading from a capsule
Use connectStore() inside a capsule to subscribe and have tiny-engine automatically unsubscribe during destroy().
class CartBadge extends Capsule {
constructor(el, options) {
super(el, options);
this.connectStore(cart, (state) => {
this.refs.count.textContent = String(state.items.length);
});
}
}Middleware
Middleware receives (action, state). Return a replacement action to transform it, false to cancel it, or nothing to continue with the current action.
const stopAtTen = (action, state) => {
if (action.type === "add" && state.items.length >= 10) {
return false;
}
return action;
};
const analytics = (action, state) => {
console.log("before", action.type, state);
return action;
};
cart.use(stopAtTen);
cart.use(analytics);