7.9 KiB
@push.rocks/smartstate
a package that handles state in a good way
Install
To install @push.rocks/smartstate
, you can use pnpm (Performant Node Package Manager). Run the following command in your terminal:
pnpm install @push.rocks/smartstate --save
This will add @push.rocks/smartstate
to your project's dependencies.
Usage
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:
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.
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
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:
enum AppStateParts {
UserState,
SettingsState
}
Now, let's create a state part within our myAppSmartState
instance:
interface IUserState {
isLoggedIn: boolean;
username?: string;
}
const userStatePart = await myAppSmartState.getStatePart<IUserState>(
AppStateParts.UserState,
{ 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
You can subscribe to changes in a state part to perform actions accordingly:
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:
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:
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
await loginUserAction.trigger({ username: 'johnDoe' });
Additional State Methods
StatePart
provides several useful methods for state management:
// 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:
const settingsStatePart = await myAppSmartState.getStatePart<ISettingsState>(
AppStateParts.SettingsState,
{ theme: 'light' }, // Initial state
'persistent' // Mode
);
// Initialize the persistent state (required for persistent mode)
await settingsStatePart.init();
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:
// 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
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.
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.
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 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
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
Lossless GmbH
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@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 Lossless GmbH of any derivative works.