2023-07-27 15:20:24 +02:00
# @push.rocks/smartstate
2026-02-02 00:52:23 +00:00
A powerful TypeScript library for elegant state management using RxJS and reactive programming patterns 🚀
## Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/ ](https://community.foss.global/ ). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/ ](https://code.foss.global/ ) account to submit Pull Requests directly.
2019-02-21 21:48:39 +01:00
2024-04-14 18:24:08 +02:00
## Install
2025-07-29 19:26:03 +00:00
To install `@push.rocks/smartstate` , you can use pnpm, npm, or yarn:
2024-04-14 18:24:08 +02:00
```bash
2025-07-29 19:26:03 +00:00
# Using pnpm (recommended)
2025-07-01 06:50:15 +00:00
pnpm install @push .rocks/smartstate --save
2025-07-29 19:26:03 +00:00
# Using npm
npm install @push .rocks/smartstate --save
# Using yarn
yarn add @push .rocks/smartstate
2024-04-14 18:24:08 +02:00
```
2019-02-21 21:48:39 +01:00
## Usage
2026-02-02 00:52:23 +00: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.
2024-04-14 18:24:08 +02:00
### Getting Started
2026-02-02 00:52:23 +00:00
Import the necessary components from the library:
2024-04-14 18:24:08 +02:00
```typescript
import { Smartstate, StatePart, StateAction } from '@push .rocks/smartstate';
```
### Creating a SmartState Instance
2026-02-02 00:52:23 +00:00
`Smartstate` acts as the container for your state parts. Think of it as the root of your state management structure:
2024-04-14 18:24:08 +02:00
```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:
2026-02-02 00:52:23 +00:00
| Mode | Description |
|------|-------------|
| `'soft'` | Default. Returns existing state part if it exists, creates new if not |
| `'mandatory'` | Requires state part to not exist, throws error if it does |
| `'force'` | Always creates new state part, overwriting any existing one |
| `'persistent'` | Like 'soft' but with WebStore persistence using IndexedDB |
2025-07-01 06:50:15 +00:00
2024-04-14 18:24:08 +02:00
### Defining State Parts
2026-02-02 00:52:23 +00:00
State parts represent separable sections of your state, making it easier to manage and modularize. Define state part names using either enums or string literal types:
2024-04-14 18:24:08 +02:00
```typescript
2025-07-19 07:18:53 +00:00
// Option 1: Using enums
2024-04-14 18:24:08 +02:00
enum AppStateParts {
2025-07-19 07:18:53 +00:00
UserState = 'UserState',
SettingsState = 'SettingsState'
2024-04-14 18:24:08 +02:00
}
2025-07-19 07:18:53 +00:00
// Option 2: Using string literal types (simpler approach)
type AppStateParts = 'UserState' | 'SettingsState';
2024-04-14 18:24:08 +02:00
```
2026-02-02 00:52:23 +00:00
Create a state part within your `Smartstate` instance:
2024-04-14 18:24:08 +02:00
```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
);
```
### Subscribing to State Changes
2026-02-02 00:52:23 +00:00
Subscribe to changes in a state part to perform actions accordingly:
2024-04-14 18:24:08 +02:00
```typescript
2025-07-29 19:26:03 +00:00
// The select() method automatically filters out undefined states
2024-04-14 18:24:08 +02:00
userStatePart.select().subscribe((currentState) => {
console.log(`User Logged In: ${currentState.isLoggedIn}` );
});
```
2026-02-02 00:52:23 +00:00
Select a specific part of your state with a selector function:
2024-04-14 18:24:08 +02:00
```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-19 07:18:53 +00:00
const newState = await loginUserAction.trigger({ username: 'johnDoe' });
2025-07-01 06:50:15 +00:00
```
2025-07-19 07:18:53 +00:00
### Dispatching Actions
There are two ways to dispatch actions:
```typescript
// Method 1: Using trigger on the action (returns promise)
const newState = await loginUserAction.trigger({ username: 'johnDoe' });
// Method 2: Using dispatchAction on the state part (returns promise)
const newState = await userStatePart.dispatchAction(loginUserAction, { username: 'johnDoe' });
```
2026-02-02 00:52:23 +00:00
Both methods return a Promise with the new state payload.
2025-07-19 07:18:53 +00:00
2025-07-01 06:50:15 +00:00
### Additional State Methods
`StatePart` provides several useful methods for state management:
```typescript
2025-07-29 19:26:03 +00:00
// Get current state (may be undefined initially)
const currentState = userStatePart.getState();
if (currentState) {
console.log('Current user:', currentState.username);
}
2025-07-01 06:50:15 +00:00
// Wait for a specific state condition
await userStatePart.waitUntilPresent();
2025-07-19 07:18:53 +00:00
// Wait for a specific property to be present
await userStatePart.waitUntilPresent(state => state.username);
2025-07-01 06:50:15 +00:00
// Setup initial state with async operations
2025-07-19 07:18:53 +00:00
await userStatePart.stateSetup(async (statePart) => {
2025-07-01 06:50:15 +00:00
const userData = await fetchUserData();
2025-07-19 07:18:53 +00:00
return { ...statePart.getState(), ...userData };
2025-07-01 06:50:15 +00:00
});
2025-07-19 07:18:53 +00:00
// Defer notification to end of call stack
userStatePart.notifyChangeCumulative();
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
Persistent state automatically:
- Saves state changes to IndexedDB
- Restores state on application restart
- Manages storage with configurable database and store names
2025-07-29 19:26:03 +00:00
### State Validation
`Smartstate` includes built-in state validation to ensure data integrity:
```typescript
2026-02-02 00:52:23 +00:00
// Basic validation (built-in) ensures state is not null or undefined
2025-07-29 19:26:03 +00:00
await userStatePart.setState(null); // Throws error: Invalid state structure
// Custom validation by extending StatePart
class ValidatedStatePart<T> extends StatePart<string, T> {
protected validateState(stateArg: any): stateArg is T {
return super.validateState(stateArg) && /* your validation */;
}
}
```
2025-07-01 06:50:15 +00:00
### Performance Optimization
2025-07-29 19:26:03 +00:00
`Smartstate` includes advanced performance optimizations:
2025-07-01 06:50:15 +00:00
2026-02-02 00:52:23 +00:00
- **🔒 Async State Hash Detection**: Uses SHA256 hashing to detect actual state changes, preventing unnecessary notifications when state values haven't truly changed
- **🚫 Duplicate Prevention**: Identical state updates are automatically filtered out
- **📦 Cumulative Notifications**: Batch multiple state changes into a single notification using `notifyChangeCumulative()`
- **🎯 Selective Subscriptions**: Use selectors to subscribe only to specific state properties
- **✨ Undefined State Filtering**: The `select()` method automatically filters out undefined states
2025-07-01 06:50:15 +00:00
### 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
2025-07-29 19:26:03 +00:00
### Complete Example
Here's a comprehensive example showcasing the power of `@push.rocks/smartstate` :
```typescript
import { Smartstate, StatePart, StateAction } from '@push .rocks/smartstate';
// Define your state structure
type AppStateParts = 'user' | 'settings' | 'cart';
interface IUserState {
isLoggedIn: boolean;
username?: string;
email?: string;
}
interface ICartState {
items: Array<{ id: string; quantity: number }>;
total: number;
}
// Create the smartstate instance
const appState = new Smartstate<AppStateParts>();
// Initialize state parts
const userState = await appState.getStatePart<IUserState>('user', {
isLoggedIn: false
});
const cartState = await appState.getStatePart<ICartState>('cart', {
items: [],
total: 0
}, 'persistent'); // Persists across sessions
// Create actions
const loginAction = userState.createAction<{ username: string; email: string }>(
async (statePart, payload) => {
// Simulate API call
await new Promise(resolve => setTimeout(resolve, 1000));
2026-02-02 00:52:23 +00:00
2025-07-29 19:26:03 +00:00
return {
isLoggedIn: true,
username: payload.username,
email: payload.email
};
}
);
// Subscribe to changes
userState.select(state => state.isLoggedIn).subscribe(isLoggedIn => {
console.log('Login status changed:', isLoggedIn);
});
// Dispatch actions
await loginAction.trigger({ username: 'john', email: 'john@example .com' });
```
2024-04-14 18:24:08 +02:00
2026-02-02 00:52:23 +00:00
## Key Features
2024-04-14 18:24:08 +02:00
2026-02-02 00:52:23 +00:00
| Feature | Description |
|---------|-------------|
| 🎯 **Type-safe ** | Full TypeScript support with intelligent type inference |
| ⚡ **Performance optimized ** | Async state hash detection prevents unnecessary re-renders |
| 💾 **Persistent state ** | Built-in IndexedDB support for state persistence |
| 🔄 **Reactive ** | Powered by RxJS for elegant async handling |
| 🧩 **Modular ** | Organize state into logical, reusable parts |
| ✅ **Validated ** | Built-in state validation with extensible validation logic |
| 🎭 **Flexible init modes ** | Choose how state parts are initialized |
| 📦 **Zero config ** | Works out of the box with sensible defaults |
2024-04-14 18:24:08 +02:00
## License and Legal Information
2026-02-02 00:52:23 +00:00
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE ](./LICENSE ) file.
2024-04-14 18:24:08 +02:00
**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
2026-02-02 00:52:23 +00:00
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 or third parties, 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 or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
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
2026-02-02 00:52:23 +00:00
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
2020-05-18 04:10:36 +00:00
2026-02-02 00:52:23 +00:00
For any legal inquiries or further information, please contact us via email at hello@task .vc.
2019-02-21 21:48:39 +01:00
2025-07-19 07:18:53 +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 Task Venture Capital GmbH of any derivative works.