Skip to content

Bang API

Chau Tran edited this page Jan 20, 2022 · 3 revisions

ngx-bang

state()

See Usages

derive()

See Derive

StatefulDirective

See Usages

State

See Usages

snapshot()

Returns the latest snapshot of a StateProxy

const state = state({count: 0});

console.log(snapshot(state)); // {count: 0}
state.count += 1;
console.log(snapshot(state)); // {count: 1}

effect()

Listen for changes on the StateProxy or specific list of property keys on the StateProxy

const state = state({count: 0, incrementCount: 0});

effect(state, ['count'], () => {
    const currentCount = snapshot(state).count;
    console.log('count changes', currentCount);
    return () => {
        console.log('cleaning up with previous count...', currentCount);
    }
});

// logs: 'count changes', 0

state.count += 1; 
// logs: 'cleanin up ...', 0
// logs: 'count changes', 1

state.count += 1;
// logs: 'cleanin up ...', 1
// logs: 'count changes', 2

state.incrementCount += 1;
// nothing logs because we're not listening to "incrementCount"

watch()

Similar to effect(). watch() does not have clean up function, so it should only be used for debugging state changes OR for logic that can run over and over on state changes without the need of cleaning up.

const state = state({count: 0, incrementCount: 0});

watch(state, (operations) => {
    console.log('state changes', operations);
});

state.count += 1;
// logs: 'state changes', [['set', 'count', 1, 0]]

state.count += 1;
state.incrementCount += 1;
// logs: 'state changes', [['set', 'count', 2, 1], ['set', 'incrementCount', 1, 0]]

You can also watch specific keys

watch(state, ['count'], (countValue) => {
    console.log('count changes', countValue);
});

state.count += 1;
// logs: 'count changes', 1

state.count += 1;
// logs: 'count changes', 2

state.incrementCount += 1;
// nothing logs

ngx-bang/async

See Async