-
Having a store, I'd like to subscribe to values changing: const store = useStore(counter);
const unsubscribe = subscribe(store.count, (count, meta) => { ... }) Subscribing to the store's actions leads to multiple challenges: const unsubscribe = onAction(Counter, "increment", (...args) => { ... })
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Hey for triggering update event you can create a utility function that uses import { Exome, subscribe } from "exome";
function subscribeToValueChanges<Store extends Exome>(
store: Store,
properyNames: (keyof Store)[],
callback: (instance: Store) => void,
) {
const previousValueMap: Partial<Record<keyof Store, any>> = {};
return subscribe(store, (instance) => {
let hasChanges = false;
for (const name of properyNames) {
const previousValue = previousValueMap[name];
const currentValue = instance[name];
if (previousValue !== currentValue) {
previousValueMap[name] = currentValue;
hasChanges = true;
}
}
if (!hasChanges) {
return;
}
callback(instance);
});
} Usage: subscribeToValueChanges(counterStore, ["count"], ({ count }) => {
console.log("update event triggered", {count});
}); Live preview of this in action: https://dune.land/dune/ef3a15a9-6590-408e-b73c-76961a02bccb As for const unsubscribe = onAction(Counter, null, (...args) => { ... }) To match correct instance with correct action, you can use args returned in callback function. Or create a utility function that does this for you. Something lie this should do: import { Exome, onAction } from "exome";
function onStoreAction<Store extends Exome>(
store: Store,
actions: (keyof Store)[],
callback: Parameters<typeof onAction<Store>>[2],
type?: Parameters<typeof onAction<Store>>[3],
) {
return onAction(store.constructor as any, null, (instance, action, payload, error) => {
if (instance !== store) {
return;
}
if ((actions as string[]).indexOf(action) === -1) {
return;
}
callback(instance as Store, action, payload, error);
}, type);
} Usage: onStoreAction(counterStore1, ["increment"], ({ count }) => {
console.log("Action `increment` on counterStore1 was triggered", {count});
}); Live preview of this in action: https://dune.land/dune/985d73db-381d-43ec-8943-45dbd10a530b |
Beta Was this translation helpful? Give feedback.
-
Nice, thanks for explanations. I'd suggest to move this helpers to the library. Subscription to a value changes is the most popular use case for reactive stores. |
Beta Was this translation helpful? Give feedback.
Hey for triggering update event you can create a utility function that uses
subscribe
and tracks changes in values across time. This should work fine with full typescript types support: