State field
State Fields are simple wrappers around storing values.
Also read key.field or Fields guide.
.get()
Returns the current value of the derived field in a StoreState.
Signature:
field.get(storeState: StoreState): FieldValue
Arguments:
StoreState
- The store state to get value from
Returns:
- The current value of field stored in the store state.
Example:
// Initialize a Field with a default value of 0
const counterField = key.field(0);
counterField.get(store.state) // 0
.initialValue
The initial value of the field.
Signature:
field.initialValue: Value
Example:
// Initialize a Field with a default value of 0
const counterField = key.field(0);
counterField.initialValue // 0
.update()
Helps build a transaction for updating the state field.
Signature:
field.update<TVal>(val: TVal | ((val: TVal) => TVal)): Transaction
Arguments:
val
- The value to update the field with. Can be a value or a function that takes the current value and returns a new value.
Returns:
Transaction
- A transaction that can be dispatched to the store.
Example:
const counterField = key.field(0);
store.dispatch(
counterField.update(1) // Update the counter to 1
)
// callback version
store.dispatch(
counterField.update((val) => val + 1) // Add one to whatever the current value is
)
It is recommended that you use actions to update state fields instead. See Actions for more information.