Skip to content

Creating a 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: [],
});

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 updates
store.setState({ count: 'invalid' }); // ❌ TypeScript error
store.setState({ count: 1 }); // ✅ OK

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],
});

Get the current state object.

const state = store.getState();
// Returns the complete state object

Update the state with a partial object. All properties not specified are preserved from the current state.

store.setState({ count: 1 });
// Multiple updates merge
store.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 listening
unsubscribe();

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 }),
};
};

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 flow
const 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 flow
export const logout = () => {
clearUser();
// Redirect to login page if needed
};

Manage application settings with persistence:

const settingsStore = createStore({
theme: 'light',
language: 'en',
notifications: true,
});
// Auto-save to localStorage on changes
const unsubscribe = settingsStore.subscribe((state) => {
localStorage.setItem('settings', JSON.stringify(state));
});