### Install @atoma/core Package Source: https://github.com/sylphxltd/atoma/blob/main/README.md Instructions for installing the @atoma/core state management library using npm, yarn, or pnpm package managers. ```bash npm install @atoma/core # or yarn add @atoma/core # or pnpm add @atoma/core ``` -------------------------------- ### Define and Use Various Atom Types in @atoma/core Source: https://github.com/sylphxltd/atoma/blob/main/README.md Comprehensive example demonstrating how to define different types of atoms (simple writable, computed/derived, async, stream, model-like with actions, and atom families) using `atom()`. It also illustrates how to create a store with `store()`, interact with atoms (get, set, use actions), manage atom family instances, and subscribe to state changes within the store. ```typescript import { atom, store } from '@atoma/core'; // --- Define Atoms --- // 1. Simple Writable State const count = atom(0); const name = atom('World'); // 2. Computed/Derived State (Read-only by default) const message = atom(get => `Hello, ${get(name)}! Count: ${get(count)}`); // 3. Async State const userData = atom(async () => { const response = await fetch('/api/user'); if (!response.ok) throw new Error('Failed to fetch user'); return await response.json(); }); // 4. Stream State (e.g., using Observables or AsyncIterables) const timer = atom(() => { // Example using a simple async generator return (async function* () { let i = 0; while (true) { await new Promise(resolve => setTimeout(resolve, 1000)); yield i++; } })(); }); // 5. Model-like State (State + Actions) const counterModel = atom({ build: () => ({ value: 0 }), // Initial state builder actions: { increment: (state) => ({ value: state.value + 1 }), decrement: (state) => ({ value: state.value - 1 }), add: (state, amount: number) => ({ value: state.value + amount }) } }); // 6. Atom Family (Parameterized State) // Automatically detected if the initializer function takes parameters const userById = atom(async (userId: string) => { const response = await fetch(`/api/users/${userId}`); if (!response.ok) throw new Error(`Failed to fetch user ${userId}`); return await response.json(); }); // --- Use in a Store --- const appStore = store(); // Get state console.log(appStore.get(message)); // Output: Hello, World! Count: 0 // Set writable state appStore.set(count, 5); console.log(appStore.get(message)); // Output: Hello, World! Count: 5 appStore.set(name, (prevName) => prevName.toUpperCase()); console.log(appStore.get(message)); // Output: Hello, WORLD! Count: 5 // Use model actions const counterActions = appStore.use(counterModel); counterActions.increment(); console.log(appStore.get(counterModel).value); // Output: 1 counterActions.add(10); console.log(appStore.get(counterModel).value); // Output: 11 // Get family instance const user1 = userById('1'); const user2 = userById('2'); // Subscribe to changes const unsubscribe = appStore.on(message, (newMessage) => { console.log('Message changed:', newMessage); }); appStore.set(count, 100); // Triggers subscription: "Message changed: Hello, WORLD! Count: 100" unsubscribe(); // Stop listening // Async/Stream access (Conceptual - UI integrations handle loading/error states) try { console.log('User 1 Data:', appStore.get(user1)); // Might initially throw or return pending state } catch (e) { console.error('Error fetching user 1:', e); } ``` -------------------------------- ### Define and Use Atoma State in TypeScript Source: https://github.com/sylphxltd/atoma/blob/main/memory-bank/systemPatterns.md This snippet demonstrates how to define various types of atoms (basic, model-like, computed, family) and interact with them using a `store` instance. It covers getting values, dispatching actions, setting values, and conceptual async/family access. ```typescript // Define state const count = atom({ build: () => 0, actions: { inc: s => s + 1 } }); const name = atom('World'); const message = atom(get => `Hello, ${get(name)}! Count: ${get(count)}`); const user = atom(async (id: string) => fetch(`/api/users/${id}`).then(r=>r.json())); // Family // Use in a store const app = store(); const counterApi = app.use(count); const user1 = user('1'); // Get specific family instance console.log(app.get(message)); // Hello, World! Count: 0 counterApi.inc(); console.log(app.get(message)); // Hello, World! Count: 1 app.set(name, 'AtomaState'); console.log(app.get(message)); // Hello, AtomaState! Count: 1 // Async/Family access (conceptual - UI hooks handle loading state) try { console.log(app.get(user1)); } catch(e) { console.log('User 1 loading...'); } ``` -------------------------------- ### Atoma Core Concepts API Reference Source: https://github.com/sylphxltd/atoma/blob/main/memory-bank/systemPatterns.md This section details the core functions and concepts of the `@atoma/core` state management library, including `atom`, `store`, `store.get`, `store.set`, `store.on`, and `store.use`. It explains their purpose and various usage patterns. ```APIDOC atom: Creates a state unit. - atom(initialValue: any): Sync atom - atom((get: (atom: any) => any) => value: any): Computed atom - atom(async (get: (atom: any) => any) => value: Promise): Async atom - atom(async () => value: Promise): Async atom (alternative) - atom(() => Observable): Stream atom - atom({ build: () => initialState: any, actions: { [key: string]: (state: any, ...args: any[]) => any } }): Model-like atom - atom((param: any) => ...): Family atom (automatically detected if initializer takes parameters) store: Creates an isolated container instance. - store(): StoreInstance StoreInstance: get(atom: any): any Retrieves the current value of an atom. - atom: The atom to retrieve the value from. - Returns: The current value. For async/stream, initial calls might trigger operations; return semantics depend on environment. set(atom: any, newValue: any | ((prev: any) => any)): void Updates a writable atom's value. - atom: The atom to update. - newValue: The new value or a function that receives the previous value and returns the new one. on(atom: any, callback: (value: any) => void): () => void Subscribes to state changes (value emissions). - atom: The atom to subscribe to. - callback: A function to be called with the new value on state changes. - Returns: An unsubscribe function. use(atom: any): any Retrieves the actions object if the atom was defined with one (model-like atoms). - atom: The model-like atom. - Returns: The actions object associated with the atom. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.