Skip to content

Bang Derive

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

You can create computed (derived) states based on existing StateProxy.

derive

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

const derived = derive({
    double: (get) => get(state).count * 2
});

console.log(snapshot(state).count); // 0
console.log(snapshot(derived).double); // 0

state.count += 5;

console.log(snapshot(state).count); // 5
console.log(snapshot(derived).double); // 10

Usage

Similar to the above example, using derive with Component states should be straightforward.

@Component({
    template: `
        <ng-container *stateful="state; let snapshot">
            {{snapshot | json}}
            {{derivedSnapshot | json}}
        </ng-container>
    `
})
export class CounterComponent {
    state = state({count: 0});
    
    derived = derive({
        double: get => get(this.state).count * 2
    });
    
    //  ๐Ÿ‘‡ create a getter for derived snapshot
    //  ๐Ÿ‘‡ Note: snapshot() is cached unless changed.
    //  ๐Ÿ‘‡ Hence, it is performant to use it as getter on the template
    get derivedSnapshot() {
        return snapshot(this.derived);
    }
}

Usage with Component Provider should also be similar.

Clone this wiki locally