@collight/immer-view
v0.0.12
Published
immer-view
Readme
🪄 immer-view
✨ A lightweight utility for working with immutable state using Immer, giving you type-safe mutable drafts during updates while keeping your data strictly immutable.
🚀 Features
- 🔒 Type-safe immutable views of your data structures
- ✏️ Mutable drafts during updates with full TypeScript support
- 🧩 Preserved class identity - updates return instances of the same class
⚡ Installation
pnpm i @collight/immer-view immer🛠 Usage
1️⃣ Create an Immutable View
import { ImmerView } from '@collight/immer-view';
interface AppState {
counter: number;
items: string[];
}
class AppView extends ImmerView<AppState> {
get itemsCount(): number {
return this.value.items.length;
}
// ✏️ Type-safe mutable method
addItem(this: MutableView<AppView>, item: string): void {
this.value.items.push(item);
}
}2️⃣ Create and Update Views
import { produceView } from '@collight/immer-view';
// 🌱 Create initial view
const initialState: AppState = { counter: 0, items: [] };
const view = new AppView(initialState);
// ✨ Update with mutation recipe
const updated = produceView(view, draft => {
draft.value.counter = 42;
draft.addItem('new item'); // Can use mutable methods
});
// 🔁 Or replace entirely
const replaced = produceView(view, new AppView({ counter: 100, items: ['a'] }));3️⃣ Preserved Class Behavior
console.log(updated instanceof AppView); // ✅ true
console.log(updated.itemsCount); // 1 - methods still workLicense
MIT
