A lightweight, type-safe state management solution for Svelte applications with built-in storage persistence.
npm install @friendofsvelte/state
app.d.ts
:declare global {
interface PodTypeRegistry {
layout: {
bg: string;
};
userSettings: {
theme: 'light' | 'dark';
fontSize: number;
};
}
}
export {};
<script lang="ts">
import { pod } from '@friendofsvelte/state';
// Initialize with value
let app = pod('layout', 'localStorage', {
bg: 'lightblue'
});
// Or use existing value
let settings = pod('userSettings');
</script>
<div style="background-color: {app.bg}">
<!-- Your content -->
</div>
pod<K>(key: K, storage?: StorageType, context?: GetTypeFromRegistry<K>)
Creates or retrieves a persistent state container.
Parameters:
key
: Unique identifier for the state containerstorage
: (Optional) Storage type - 'localStorage' or 'sessionStorage' (default: 'localStorage')context
: (Optional) Initial state valueReturns:
GetTypeFromRegistry<K>
Pod State provides complete type safety through TypeScript. The global PodTypeRegistry
interface allows you to define types for all your state containers in one place:
interface PodTypeRegistry {
layout: {
bg: string;
};
userSettings: {
theme: 'light' | 'dark';
fontSize: number;
};
}
<script lang="ts">
import { pod } from '@friendofsvelte/state';
let app = pod('layout', 'localStorage', {
bg: 'lightblue'
});
</script>
<button onclick={() => app.bg = 'lightgreen'}>
Change Background
</button>
<!-- ComponentA.svelte -->
<script>
import { pod } from '@friendofsvelte/state';
let settings = pod('userSettings');
</script>
<!-- ComponentB.svelte -->
<script>
import { pod } from '@friendofsvelte/state';
let settings = pod('userSettings');
// Will automatically sync with ComponentA
</script>
Pod State includes a test suite to ensure reliability. Run tests with:
npm test
Contributions are welcome! Please feel free to submit a Pull Request.
MIT License - see LICENSE file for details