Store Event
We can trigger something when the store got a new subscriber or lost a subscriber.
Here we called it a "store event".
There were 4 event can be used, onFirstSubscribe
, onSubscribe
, onUnsubscribe
, and onLastUnsubscribe
.
const useCatStore = createStore(
({ set }) => ({
age: 0,
isSleeping: false,
increaseAge: () => set((state) => ({ age: state.age + 1 })),
reset: () => set({ age: 0, isSleeping: false }),
}),
{
onFirstSubscribe: (state) => {
console.log('onFirstSubscribe', state);
},
onSubscribe: (state) => {
console.log('onSubscribe', state);
},
onUnsubscribe: (state) => {
console.log('onUnsubscribe', state);
},
onLastUnsubscribe: (state) => {
console.log('onLastUnsubscribe', state);
},
},
);
Let's go wild using IIFE.
const useCatStore = createStore(
({ set }) => ({
age: 0,
isSleeping: false,
increaseAge: () => set((state) => ({ age: state.age + 1 })),
reset: () => set({ age: 0, isSleeping: false }),
}),
(() => {
const validateCat = () => {
console.info('Window focus event triggered...');
const { age } = useCatStore.get();
if (age > 5) useCatStore.set({ age: 1 });
};
return {
onFirstSubscribe: () => window.addEventListener('focus', validateCat),
onLastUnsubscribe: () => window.removeEventListener('focus', validateCat),
};
})(),
);