Files
smartstate/readme.hints.md

52 lines
2.6 KiB
Markdown
Raw Normal View History

# 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:
1. `stateAction.trigger(payload)` - returns Promise<TStatePayload>
2. `await statePart.dispatchAction(stateAction, payload)` - returns Promise<TStatePayload>
- Both methods return the same Promise, providing flexibility in usage
### State Management Methods
- `select()` - returns Observable with startWith current state, filters undefined states
- `waitUntilPresent()` - waits for specific state condition
- `stateSetup()` - async state initialization with cumulative defer
- `notifyChangeCumulative()` - defers notification to end of call stack
- `getState()` - returns current state or undefined
- `setState()` - 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+)
1. Fixed state hash bug - now properly compares hash values instead of promises
2. Fixed state initialization merge order - initial state now takes precedence
3. Ensured stateStore is properly typed as potentially undefined
4. Simplified init mode logic with clear behavior for each mode
5. Added state validation with extensible validateState() method
6. Made notifyChange() async to support proper hash comparison
7. Updated select() to filter undefined states