Files
smartstate/readme.md

218 lines
7.9 KiB
Markdown
Raw Permalink Normal View History

2023-07-27 15:20:24 +02:00
# @push.rocks/smartstate
2019-02-21 21:48:39 +01:00
a package that handles state in a good way
2024-04-14 18:24:08 +02:00
## Install
2025-07-01 06:50:15 +00:00
To install `@push.rocks/smartstate`, you can use pnpm (Performant Node Package Manager). Run the following command in your terminal:
2024-04-14 18:24:08 +02:00
```bash
2025-07-01 06:50:15 +00:00
pnpm install @push.rocks/smartstate --save
2024-04-14 18:24:08 +02:00
```
This will add `@push.rocks/smartstate` to your project's dependencies.
2019-02-21 21:48:39 +01:00
## Usage
2024-04-14 18:24:08 +02:00
The `@push.rocks/smartstate` library provides an elegant way to handle state within your JavaScript or TypeScript projects, leveraging the power of Reactive Extensions (RxJS) and a structured state management strategy. In the following sections, we will explore the comprehensive capabilities of this package and how to effectively use them in various scenarios, ensuring a robust state management pattern in your applications.
### Getting Started
First, let's import the necessary components from the library:
```typescript
import { Smartstate, StatePart, StateAction } from '@push.rocks/smartstate';
```
### Creating a SmartState Instance
`Smartstate` acts as the container for your state parts. You can consider it as the root of your state management structure.
```typescript
const myAppSmartState = new Smartstate<YourStatePartNamesEnum>();
```
2025-07-01 06:50:15 +00:00
### 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
2024-04-14 18:24:08 +02:00
### 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.
Define an enum for state part names for better management:
```typescript
enum AppStateParts {
UserState,
SettingsState
}
```
Now, let's create a state part within our `myAppSmartState` instance:
```typescript
interface IUserState {
isLoggedIn: boolean;
username?: string;
}
const userStatePart = await myAppSmartState.getStatePart<IUserState>(
AppStateParts.UserState,
2025-07-01 06:50:15 +00:00
{ isLoggedIn: false }, // Initial state
'soft' // Init mode (optional, defaults to 'soft')
2024-04-14 18:24:08 +02:00
);
2025-07-01 06:50:15 +00:00
// For persistent state parts, you must call init()
if (mode === 'persistent') {
await userStatePart.init();
}
2024-04-14 18:24:08 +02:00
```
### Subscribing to State Changes
You can subscribe to changes in a state part to perform actions accordingly:
```typescript
userStatePart.select().subscribe((currentState) => {
console.log(`User Logged In: ${currentState.isLoggedIn}`);
});
```
If you need to select a specific part of your state, you can pass a selector function:
```typescript
userStatePart.select(state => state.username).subscribe((username) => {
if (username) {
console.log(`Current user: ${username}`);
}
});
```
### Modifying State with Actions
Create actions to modify the state in a controlled manner:
```typescript
interface ILoginPayload {
username: string;
}
const loginUserAction = userStatePart.createAction<ILoginPayload>(async (statePart, payload) => {
return { ...statePart.getState(), isLoggedIn: true, username: payload.username };
});
// Dispatch the action to update the state
2025-07-01 06:50:15 +00:00
await loginUserAction.trigger({ username: 'johnDoe' });
```
### Additional State Methods
`StatePart` provides several useful methods for state management:
```typescript
// 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
});
2024-04-14 18:24:08 +02:00
```
2025-07-01 06:50:15 +00:00
### Persistent State with WebStore
2024-04-14 18:24:08 +02:00
2025-07-01 06:50:15 +00:00
`Smartstate` supports persistent states using WebStore (IndexedDB-based storage), allowing you to maintain state across sessions:
2024-04-14 18:24:08 +02:00
```typescript
2025-07-01 06:50:15 +00:00
const settingsStatePart = await myAppSmartState.getStatePart<ISettingsState>(
2024-04-14 18:24:08 +02:00
AppStateParts.SettingsState,
{ theme: 'light' }, // Initial state
'persistent' // Mode
);
2025-07-01 06:50:15 +00:00
// Initialize the persistent state (required for persistent mode)
await settingsStatePart.init();
2024-04-14 18:24:08 +02:00
```
2025-07-01 06:50:15 +00:00
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);
});
```
2024-04-14 18:24:08 +02:00
### 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.
2025-07-01 06:50:15 +00:00
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
2024-04-14 18:24:08 +02:00
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.
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
2025-07-01 06:50:15 +00:00
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.
2020-05-18 04:10:36 +00:00
2024-04-14 18:24:08 +02:00
### Company Information
2020-05-18 04:10:36 +00:00
2025-07-01 06:50:15 +00:00
Lossless GmbH
2024-04-14 18:24:08 +02:00
Registered at District court Bremen HRB 35230 HB, Germany
2020-05-18 04:10:36 +00:00
2025-07-01 06:50:15 +00:00
For any legal inquiries or if you require further information, please contact us via email at hello@lossless.com.
2019-02-21 21:48:39 +01:00
2025-07-01 06:50:15 +00:00
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.