createStore
Signature
Section titled “Signature”function createStore<State>( initialState: State, options?: CreateStoreOptions<State>): Store<State>;Parameters
Section titled “Parameters”initialState
Section titled “initialState”The initial state object containing your application’s data. Can be any JavaScript object.
const store = createStore({ count: 0, user: { name: 'John', age: 30 }, items: [],});options (optional)
Section titled “options (optional)”Configure store behavior and adapters.
Options Interface
Section titled “Options Interface”interface CreateStoreOptions<State> { adapter?: StorageAdapter; prefix?: string; middleware?: Middleware[]; ttl?: number | Date | Temporal.Duration | Temporal.Instant; expiryFormat?: 'iso' | 'epoch'; scope?: 'tab' | 'global';}| Option | Type | Description |
|---|---|---|
adapter |
StorageAdapter |
Persist state to storage (localStorage, cookies, URL, etc.) |
prefix |
string |
Prefix for store keys (useful when creating multiple stores) |
middleware |
Middleware[] |
Array of middleware functions |
ttl |
number | Date | Temporal.Duration | Temporal.Instant |
Time-to-live for state expiration |
expiryFormat |
'iso' | 'epoch' |
Format for TTL timestamps |
scope |
'tab' | 'global' |
Storage scope (tab-local or global) |
Methods
Section titled “Methods”getState(): State
Section titled “getState(): State”Get the current state object.
const state = store.getState();// Returns: { count: 0, user: {...}, items: [...] }setState(updates: Partial<State>): void
Section titled “setState(updates: Partial<State>): void”Update the state with a partial object. Merges with existing state.
store.setState({ count: 1 });// Result: { count: 1, user: {...}, items: [...] }
store.setState({ count: 2, user: { name: 'Jane' }});// Result: { count: 2, user: { name: 'Jane', age: 30 }, items: [...] }subscribe(listener: (state: State) => void): () => void
Section titled “subscribe(listener: (state: State) => void): () => void”Listen to state changes. Returns unsubscribe function.
const unsubscribe = store.subscribe((state) => { console.log('State updated:', state);});
// Later, stop listening:unsubscribe();Typed Stores
Section titled “Typed Stores”Generic Syntax
Section titled “Generic Syntax”Use TypeScript generics for type safety:
interface AppState { count: number; user: { name: string; age: number };}
const store = createStore<AppState>({ count: 0, user: { name: 'John', age: 30 },});
// Type-safe operationsstore.setState({ count: 1 }); // ✅ OKstore.setState({ invalid: 'bad' }); // ❌ TypeScript errorType Utilities
Section titled “Type Utilities”Extract types from stores:
type MyState = InferState<typeof store>;type MyKeys = keyof MyState;Middleware Integration
Section titled “Middleware Integration”import { createStore, loggerMiddleware, validateMiddleware } from '@standard-store/store';
const store = createStore({ count: 0 }, { middleware: [ loggerMiddleware, // Log all operations validateMiddleware((state) => { if (state.count < 0) throw new Error('Count cannot be negative'); }), ],});Adapter Integration
Section titled “Adapter Integration”import { createStore } from '@standard-store/store';import { localStorageAdapter } from '@standard-store/adapters';
const store = createStore({ count: 0 }, { adapter: localStorageAdapter('my-store'),});
// State persists across page reloadsstore.setState({ count: 1 });// State automatically saved to localStorageExamples
Section titled “Examples”Counter Store
Section titled “Counter Store”const counterStore = createStore({ count: 0 });
export const useCounter = () => { const state = counterStore.getState(); return { count: state.count, increment: () => counterStore.setState({ count: state.count + 1 }), decrement: () => counterStore.setState({ count: state.count - 1 }), reset: () => counterStore.setState({ count: 0 }), };};User Store with Persistence
Section titled “User Store with Persistence”interface User { id: string; name: string; email: string;}
const userStore = createStore<{ currentUser: User | null }>({ currentUser: null,}, { adapter: localStorageAdapter('user-store'),});
export const login = (user: User) => { userStore.setState({ currentUser: user });};
export const logout = () => { userStore.setState({ currentUser: null });};See Also
Section titled “See Also”- createStoreHook - React hook for stores
- Adapters - Storage adapters reference
- Middleware - Middleware reference