UNPKG

stimulus-store

Version:

Lightweight state management for Stimulus.js

41 lines (40 loc) 1.73 kB
import type { StoreController } from 'types'; /** * useStore Function * The useStore function simplifies the process of subscribing to and handling updates from multiple store instances * within a Stimulus controller. It also allows direct access to store values on the controller. * How It Works: * 1. Retrieves the stores from the controller's constructor. * 2. Iterates over the stores. * 3. Identifies the type of each store and constructs an update method name. * 4. Creates update methods for stores if corresponding onStoreUpdate methods exist on the controller. * 5. Dynamically assigns update methods to the controller with specific names based on store types. * 6. Subscribes update methods to stores to handle updates. * 7. Allows direct access to store values on the controller. * 8. Enhances the controller's disconnect method to include cleanup for all subscriptions. * * Usage Example: * ```javascript * import { Controller } from "@hotwired/stimulus"; * import { useStore } from "stimulus-store"; * import { myStore } from "./stores/myStore"; // Import your store class * * export default class extends Controller { * static stores = [myStore]; * * connect() { * // Use the useStore function to subscribe to specific stores * useStore(this); * } * * // Implement specific update methods for each store * onMyStoreUpdate() { * // Handle updates for MyStore * console.log("MyStore updated:", this.myStoreValue); * } * } * ``` * @param {Object} controller - The Stimulus controller instance that wants to subscribe to the stores. * @template T - The type of data stored in the stores. */ export declare function useStore(controller: StoreController): void;