-
Notifications
You must be signed in to change notification settings - Fork 6
Bang Derive
Chau Tran edited this page Jan 20, 2022
·
3 revisions
You can create computed (derived) states based on existing StateProxy
.
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
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.