createKey
Signature
createKey(name:string, dependencies?: Slice[])
Arguments:
name
- Name of the slice.dependencies
- An optional array of slices that this slice depends on.
Returns:
- A Key object.
Example
import { createKey } from '@nalanda/core';
const key = createKey('mySlice', [someSlice, someOtherSlice]);
Key
The following methods are available on the key
object.
.derive()
Creates a new derived field object.
Signature:
key.derive<T>(compute: (storeState: StoreState) => T, options?: DeriveOptions): DerivedField<T>
Arguments:
-
compute
- A function that computes the derived value. -
options?
- An optional object containing the following options.equal
-(a: T, b: T) => boolean
A comparator function that compares the previous and current value of the derived field. If the comparator returns true, the derived field is not updated. Defaults toObject.is
.
Returns:
Example:
const counterField = key.field(0);
const positiveNumberField = key.derive((store) => {
return counterField.get(state) > 0;
}, {
equal: (a, b) => a === b,
});
.effect()
Creates a new effect object.
Signature:
key.effect(effect: (store: EffectStore) => void | Promise<void>) : string
Arguments:
effect
- The callback to run as a side effect. The first argument of this callback is an EffectStore.
Returns:
string
- The name of the effect.
Example:
const counter = key.field(0);
key.effect((store) => {
// This will run whenever the counter value changes
const counterValue = counter.track(store);
console.log(`The counter value is ${counterValue}`);
});
.field()
Creates a new field object.
Signature:
key.field(initialValue: any, options)
Arguments:
initialValue
- Initial value of the field.options
:equal
:(a: T, b: T) => boolean
A comparator function that compares the previous and current value of the field. If the comparator returns true, the field is not updated. Defaults toObject.is
.
Returns:
.slice()
Creates a new slice object.
Signature:
key.slice({ ...fields, ...actions });
Arguments:
object
: An object containing the fields or actions you want to expose externally.
Returns:
Example:
export const countSlice = key.slice({
// fields
count,
// actions
increment,
});
Note: Only the slice should be exported from your file.
.transaction()
Creates a new transaction object which is used to update the slice state.
Signature:
key.transaction();
Returns:
- A transaction object.
Example:
function increment() {
const txn = key.transaction();
return txn.step((state: StoreState) => {
return state.apply(count.update((c) => c + 1));
});
}