import tap from 'tap'; import u from '@yanick/updeep'; import { Updux } from './Updux.js'; import { action } from './actions.js'; tap.test('subscriptions', async () => { const inc = action('inc'); const set_copy = action('set_copy'); const dux = new Updux({ initial: { x: 0, copy: 0, }, actions: { inc, set_copy, }, mutations: { inc: (payload) => u({ x: (x) => x + 1 }), set_copy: (copy) => u({ copy }), }, }); dux.addSubscription((store) => (state, previous, unsubscribe) => { if (state.x > 2) return unsubscribe(); store.dispatch(set_copy(state.x)); }); const store = dux.createStore(); store.dispatch(inc()); tap.same(store.getState(), { x: 1, copy: 1 }); store.dispatch(inc()); store.dispatch(inc()); tap.same(store.getState(), { x: 3, copy: 2 }, 'we unsubscribed'); }); tap.test('subduxes subscriptions', async (t) => { const inc_top = action('inc_top'); const inc_bar = action('inc_bar'); const transform_bar = action('transform_bar'); const bar = new Updux({ initial: 'a', actions: { inc_bar, transform_bar }, mutations: { inc_bar: () => (state) => state + 'a', transform_bar: (outcome) => () => outcome, }, subscriptions: [ (store) => (state, previous, unsubscribe) => { if (state.length <= 2) return; unsubscribe(); store.dispatch(transform_bar('look at ' + state)); }, ], }); const dux = new Updux({ initial: { count: 0, }, subduxes: { bar }, actions: { inc_top, }, mutations: { inc_top: () => u({ count: (count) => count + 1 }), }, effects: { '*': () => (next) => (action) => { next(action); }, }, subscriptions: [ (store) => { return ({ count }, { count: previous } = {}) => { if (count !== previous) { previous = count; store.dispatch.inc_bar(); } }; }, ], }); const store = dux.createStore(); store.dispatch(inc_top()); store.dispatch(inc_top()); t.same(store.getState(), { count: 2, bar: 'look at look at aaa', }); store.dispatch(inc_top()); t.same(store.getState(), { count: 3, bar: 'look at look at aaaa', }); });