
Security News
Open Source Maintainers Feeling the Weight of the EU’s Cyber Resilience Act
The EU Cyber Resilience Act is prompting compliance requests that open source maintainers may not be obligated or equipped to handle.
@push.rocks/smartstate
Advanced tools
a package that handles state in a good way
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.
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.
First, let's import the necessary components from the library:
import { Smartstate, StatePart, StateAction } from '@push.rocks/smartstate';
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>();
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 IndexedDBState 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();
}
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}`);
}
});
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' });
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
});
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:
Smartstate
includes built-in performance optimizations:
notifyChangeCumulative()
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);
});
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:
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.
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.
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.
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.
FAQs
A package for handling and managing state in applications.
We found that @push.rocks/smartstate demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
The EU Cyber Resilience Act is prompting compliance requests that open source maintainers may not be obligated or equipped to handle.
Security News
Crates.io adds Trusted Publishing support, enabling secure GitHub Actions-based crate releases without long-lived API tokens.
Research
/Security News
Undocumented protestware found in 28 npm packages disrupts UI for Russian-language users visiting Russian and Belarusian domains.