2.6 KiB
2.6 KiB
Smartstate Implementation Notes
Current API (as of v2.0.24+)
State Part Initialization
- State parts can be created with different init modes: 'soft' (default), 'mandatory', 'force', 'persistent'
- 'soft' - returns existing state part if exists, creates new if not
- 'mandatory' - requires state part to not exist, fails if it does
- 'force' - always creates new state part, overwriting any existing
- 'persistent' - like 'soft' but with WebStore persistence (IndexedDB)
- Persistent mode automatically calls init() internally - no need to call it manually
- State merge order fixed: initial state takes precedence over stored state
Actions
- Actions are created with
createAction()
method - Two ways to dispatch actions:
stateAction.trigger(payload)
- returns Promiseawait statePart.dispatchAction(stateAction, payload)
- returns Promise
- Both methods return the same Promise, providing flexibility in usage
State Management Methods
select()
- returns Observable with startWith current state, filters undefined stateswaitUntilPresent()
- waits for specific state conditionstateSetup()
- async state initialization with cumulative defernotifyChangeCumulative()
- defers notification to end of call stackgetState()
- returns current state or undefinedsetState()
- validates state before setting, notifies only on actual changes
State Hash Detection
- Uses SHA256 hash to detect actual state changes
- Fixed: Hash comparison now properly awaits async hash calculation
- Prevents duplicate notifications for identical state values
notifyChange()
is now async to support proper hash comparison
State Validation
- Basic validation ensures state is not null/undefined
validateState()
method can be overridden in subclasses for custom validation- Validation runs on both setState() and when loading from persistent storage
Type System
- Can use either enums or string literal types for state part names
- Test uses simple string types:
type TMyStateParts = 'testStatePart'
- State can be undefined initially, handled properly in select() and other methods
Recent Fixes (v2.0.24+)
- Fixed state hash bug - now properly compares hash values instead of promises
- Fixed state initialization merge order - initial state now takes precedence
- Ensured stateStore is properly typed as potentially undefined
- Simplified init mode logic with clear behavior for each mode
- Added state validation with extensible validateState() method
- Made notifyChange() async to support proper hash comparison
- Updated select() to filter undefined states