Compare commits
2 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
aa6766ef36 | ||
|
b0442e1227 |
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@push.rocks/smartstate",
|
"name": "@push.rocks/smartstate",
|
||||||
"version": "2.0.20",
|
"version": "2.0.21",
|
||||||
"private": false,
|
"private": false,
|
||||||
"description": "A package for handling and managing state in applications.",
|
"description": "A package for handling and managing state in applications.",
|
||||||
"main": "dist_ts/index.js",
|
"main": "dist_ts/index.js",
|
||||||
|
106
readme.md
106
readme.md
@@ -3,10 +3,10 @@ a package that handles state in a good way
|
|||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
To install `@push.rocks/smartstate`, you can use npm (Node Package Manager). Run the following command in your terminal:
|
To install `@push.rocks/smartstate`, you can use pnpm (Performant Node Package Manager). Run the following command in your terminal:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install @push.rocks/smartstate --save
|
pnpm install @push.rocks/smartstate --save
|
||||||
```
|
```
|
||||||
|
|
||||||
This will add `@push.rocks/smartstate` to your project's dependencies.
|
This will add `@push.rocks/smartstate` to your project's dependencies.
|
||||||
@@ -31,6 +31,15 @@ import { Smartstate, StatePart, StateAction } from '@push.rocks/smartstate';
|
|||||||
const myAppSmartState = new Smartstate<YourStatePartNamesEnum>();
|
const myAppSmartState = new Smartstate<YourStatePartNamesEnum>();
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Understanding Init Modes
|
||||||
|
|
||||||
|
When creating state parts, you can specify different initialization modes:
|
||||||
|
|
||||||
|
- **`'soft'`** - Allows existing state parts to remain (default behavior)
|
||||||
|
- **`'mandatory'`** - Fails if there's an existing state part with the same name
|
||||||
|
- **`'force'`** - Overwrites any existing state part
|
||||||
|
- **`'persistent'`** - Enables WebStore persistence using IndexedDB
|
||||||
|
|
||||||
### Defining State Parts
|
### Defining State Parts
|
||||||
|
|
||||||
State parts represent separable sections of your state, making it easier to manage and modularize. For example, you may have a state part for user data and another for application settings.
|
State parts represent separable sections of your state, making it easier to manage and modularize. For example, you may have a state part for user data and another for application settings.
|
||||||
@@ -54,8 +63,14 @@ interface IUserState {
|
|||||||
|
|
||||||
const userStatePart = await myAppSmartState.getStatePart<IUserState>(
|
const userStatePart = await myAppSmartState.getStatePart<IUserState>(
|
||||||
AppStateParts.UserState,
|
AppStateParts.UserState,
|
||||||
{ isLoggedIn: false } // Initial state
|
{ isLoggedIn: false }, // Initial state
|
||||||
|
'soft' // Init mode (optional, defaults to 'soft')
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// For persistent state parts, you must call init()
|
||||||
|
if (mode === 'persistent') {
|
||||||
|
await userStatePart.init();
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Subscribing to State Changes
|
### Subscribing to State Changes
|
||||||
@@ -92,28 +107,93 @@ const loginUserAction = userStatePart.createAction<ILoginPayload>(async (statePa
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Dispatch the action to update the state
|
// Dispatch the action to update the state
|
||||||
loginUserAction.trigger({ username: 'johnDoe' });
|
await loginUserAction.trigger({ username: 'johnDoe' });
|
||||||
```
|
```
|
||||||
|
|
||||||
### Persistent State
|
### Additional State Methods
|
||||||
|
|
||||||
`Smartstate` supports the concept of persistent states, where you can maintain state across sessions. To utilize this, specify a persistent mode when getting a state part:
|
`StatePart` provides several useful methods for state management:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
const settingsStatePart = await myAppSmartState.getStatePart<AppStateParts, ISettingsState>(
|
// Wait for a specific state condition
|
||||||
|
await userStatePart.waitUntilPresent();
|
||||||
|
|
||||||
|
// Setup initial state with async operations
|
||||||
|
await userStatePart.stateSetup(async (state) => {
|
||||||
|
// Perform async initialization
|
||||||
|
const userData = await fetchUserData();
|
||||||
|
return { ...state, ...userData };
|
||||||
|
});
|
||||||
|
|
||||||
|
// Batch multiple state changes for cumulative notification
|
||||||
|
userStatePart.notifyChangeCumulative(() => {
|
||||||
|
// Multiple state changes here will result in a single notification
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Persistent State with WebStore
|
||||||
|
|
||||||
|
`Smartstate` supports persistent states using WebStore (IndexedDB-based storage), allowing you to maintain state across sessions:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const settingsStatePart = await myAppSmartState.getStatePart<ISettingsState>(
|
||||||
AppStateParts.SettingsState,
|
AppStateParts.SettingsState,
|
||||||
{ theme: 'light' }, // Initial state
|
{ theme: 'light' }, // Initial state
|
||||||
'persistent' // Mode
|
'persistent' // Mode
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Initialize the persistent state (required for persistent mode)
|
||||||
|
await settingsStatePart.init();
|
||||||
```
|
```
|
||||||
|
|
||||||
This mode ensures that the state is saved and can be reloaded even after the application restarts, providing a seamless user experience.
|
Persistent state automatically:
|
||||||
|
- Saves state changes to IndexedDB
|
||||||
|
- Restores state on application restart
|
||||||
|
- Manages storage with configurable database and store names
|
||||||
|
|
||||||
|
### Performance Optimization
|
||||||
|
|
||||||
|
`Smartstate` includes built-in performance optimizations:
|
||||||
|
|
||||||
|
- **State Hash Detection**: Uses SHA256 hashing to detect actual state changes, preventing unnecessary notifications when state values haven't truly changed
|
||||||
|
- **Cumulative Notifications**: Batch multiple state changes into a single notification using `notifyChangeCumulative()`
|
||||||
|
- **Selective Subscriptions**: Use selectors to subscribe only to specific state properties
|
||||||
|
|
||||||
|
### RxJS Integration
|
||||||
|
|
||||||
|
`Smartstate` leverages RxJS for reactive state management:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// State is exposed as an RxJS Subject
|
||||||
|
const stateObservable = userStatePart.select();
|
||||||
|
|
||||||
|
// Automatically starts with current state value
|
||||||
|
stateObservable.subscribe((state) => {
|
||||||
|
console.log('Current state:', state);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Use selectors for specific properties
|
||||||
|
userStatePart.select(state => state.username)
|
||||||
|
.pipe(
|
||||||
|
distinctUntilChanged(),
|
||||||
|
filter(username => username !== undefined)
|
||||||
|
)
|
||||||
|
.subscribe(username => {
|
||||||
|
console.log('Username changed:', username);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
### Comprehensive Usage
|
### Comprehensive Usage
|
||||||
|
|
||||||
Putting it all together, `@push.rocks/smartstate` offers a flexible and powerful pattern for managing application state. By modularizing state parts, subscribing to state changes, and controlling state modifications through actions, developers can maintain a clean and scalable architecture. Combining these strategies with persistent states unlocks the full potential for creating dynamic and user-friendly applications.
|
Putting it all together, `@push.rocks/smartstate` offers a flexible and powerful pattern for managing application state. By modularizing state parts, subscribing to state changes, and controlling state modifications through actions, developers can maintain a clean and scalable architecture. Combining these strategies with persistent states unlocks the full potential for creating dynamic and user-friendly applications.
|
||||||
|
|
||||||
Remember to leverage TypeScript for its excellent support for types and interfaces, enhancing your development experience with type checking and IntelliSense, ensuring a more reliable and maintainable codebase.
|
Key features:
|
||||||
|
- **Type-safe state management** with full TypeScript support
|
||||||
|
- **Reactive state updates** using RxJS observables
|
||||||
|
- **Persistent state** with IndexedDB storage
|
||||||
|
- **Performance optimized** with state hash detection
|
||||||
|
- **Modular architecture** with separate state parts
|
||||||
|
- **Action-based updates** for predictable state modifications
|
||||||
|
|
||||||
For more complex scenarios, consider combining multiple state parts, creating hierarchical state structures, and integrating with other state management solutions as needed. With `@push.rocks/smartstate`, the possibilities are vast, empowering you to tailor the state management approach to fit the unique requirements of your project.
|
For more complex scenarios, consider combining multiple state parts, creating hierarchical state structures, and integrating with other state management solutions as needed. With `@push.rocks/smartstate`, the possibilities are vast, empowering you to tailor the state management approach to fit the unique requirements of your project.
|
||||||
|
|
||||||
@@ -125,13 +205,13 @@ This repository contains open-source code that is licensed under the MIT License
|
|||||||
|
|
||||||
### Trademarks
|
### Trademarks
|
||||||
|
|
||||||
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
|
This project is owned and maintained by Lossless GmbH. The names and logos associated with Lossless GmbH and any related products or services are trademarks of Lossless GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Lossless GmbH's Trademark Guidelines, and any usage must be approved in writing by Lossless GmbH.
|
||||||
|
|
||||||
### Company Information
|
### Company Information
|
||||||
|
|
||||||
Task Venture Capital GmbH
|
Lossless GmbH
|
||||||
Registered at District court Bremen HRB 35230 HB, Germany
|
Registered at District court Bremen HRB 35230 HB, Germany
|
||||||
|
|
||||||
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
For any legal inquiries or if you require further information, please contact us via email at hello@lossless.com.
|
||||||
|
|
||||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Lossless GmbH of any derivative works.
|
||||||
|
Reference in New Issue
Block a user