Creating a Store
Basic Store
Section titled “Basic Store”Create a simple store with initial state:
import { createStore } from '@standard-store/store';
const store = createStore({ count: 0, user: { name: 'John', age: 30 }, items: [],});Typed Store
Section titled “Typed Store”Use TypeScript generics for type safety. This prevents invalid updates at compile time:
interface AppState { count: number; user: { name: string; age: number }; items: string[];}
const store = createStore<AppState>({ count: 0, user: { name: 'John', age: 30 }, items: [],});
// Type checking ensures correct updatesstore.setState({ count: 'invalid' }); // ❌ TypeScript errorstore.setState({ count: 1 }); // ✅ OKWith Options
Section titled “With Options”Configure store behavior with options:
import { localStorageAdapter } from '@standard-store/adapters';import { loggerMiddleware } from '@standard-store/store/middleware/logger';
const store = createStore(initialState, { adapter: localStorageAdapter('my-store'), prefix: 'my-app:', middleware: [loggerMiddleware],});Store Methods Reference
Section titled “Store Methods Reference”getState(): State
Section titled “getState(): State”Get the current state object.
const state = store.getState();// Returns the complete state objectsetState(updates: Partial<State>): void
Section titled “setState(updates: Partial<State>): void”Update the state with a partial object. All properties not specified are preserved from the current state.
store.setState({ count: 1 });
// Multiple updates mergestore.setState({ count: 2 }); // { count: 2, user: {...}, items: [...] }subscribe(listener: (state: State) => void): () => void
Section titled “subscribe(listener: (state: State) => void): () => void”Listen to state changes. Returns an unsubscribe function to stop listening.
const unsubscribe = store.subscribe((state) => { console.log('State updated:', state);});
// Stop listeningunsubscribe();Examples
Section titled “Examples”Counter Store
Section titled “Counter Store”Create a counter with derived actions:
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 Authentication Flow
Section titled “User Store with Authentication Flow”Manage user authentication state:
interface User { id: string; name: string; email: string;}
const userStore = createStore<{ currentUser: User | null }>({ currentUser: null,});
export const setUser = (user: User) => { userStore.setState({ currentUser: user });};
export const clearUser = () => { userStore.setState({ currentUser: null });};
// Login flowconst login = async (email: string, password: string) => { // Simulate API call const response = await fetch('/api/login', { method: 'POST', body: JSON.stringify({ email, password }), });
const user = await response.json(); setUser(user);};
// Logout flowexport const logout = () => { clearUser(); // Redirect to login page if needed};Settings Store
Section titled “Settings Store”Manage application settings with persistence:
const settingsStore = createStore({ theme: 'light', language: 'en', notifications: true,});
// Auto-save to localStorage on changesconst unsubscribe = settingsStore.subscribe((state) => { localStorage.setItem('settings', JSON.stringify(state));});See Also
Section titled “See Also”- Adapters - Storage adapters guide
- Middleware - Middleware integration guide