3.3 KiB
3.3 KiB
ExpenseStore Usage Guide
Overview
The expenseStore is a Svelte writable store that manages expense state for the InstantSplit application. This guide explains how to use the store correctly with TypeScript.
Common Errors and Solutions
Error: Property does not exist on type 'Writable'
If you see errors like:
Property 'setDescription' does not exist on type 'Writable<ExpenseStore>'.
Property 'addParticipant' does not exist on type 'Writable<ExpenseStore>'.
Property 'calculateSplits' does not exist on type 'Writable<ExpenseStore>'.
This happens because TypeScript doesn't recognize custom methods added to Svelte stores.
Correct Usage Pattern
Always use the update method to modify the store in a type-safe way:
Instead of:
// ❌ This won't work with TypeScript
expenseStore.setDescription('New description');
expenseStore.addParticipant();
expenseStore.calculateSplits();
Do this:
// ✅ Use the update method
expenseStore.update(store => ({
...store,
currentExpense: {
...store.currentExpense,
description: 'New description'
}
}));
Common Operations
Setting the description
expenseStore.update(store => ({
...store,
currentExpense: {
...store.currentExpense,
description: value
}
}));
Setting the amount
expenseStore.update(store => ({
...store,
currentExpense: {
...store.currentExpense,
totalAmount: value
}
}));
Adding a participant
expenseStore.update(store => {
const newParticipant = {
id: Date.now().toString(36) + Math.random().toString(36).substr(2),
name: '',
address: '',
amount: '0'
};
return {
...store,
currentExpense: {
...store.currentExpense,
participants: [...store.currentExpense.participants, newParticipant]
}
};
});
Removing a participant
expenseStore.update(store => ({
...store,
currentExpense: {
...store.currentExpense,
participants: store.currentExpense.participants.filter(p => p.id !== participantId)
}
}));
Updating a participant
expenseStore.update(store => ({
...store,
currentExpense: {
...store.currentExpense,
participants: store.currentExpense.participants.map(p =>
p.id === participantId ? { ...p, [field]: value } : p
)
}
}));
Recalculating splits (equal)
expenseStore.update(store => {
const totalAmount = parseFloat(store.currentExpense.totalAmount) || 0;
const participants = store.currentExpense.participants;
const totalPeople = participants.length + 1; // +1 for creator
if (totalAmount <= 0 || totalPeople <= 1) {
return store; // No changes if invalid data
}
const amountPerPerson = totalAmount / totalPeople;
const amountStr = amountPerPerson.toFixed(7);
return {
...store,
currentExpense: {
...store.currentExpense,
participants: participants.map(p => ({
...p,
amount: amountStr
}))
}
};
});
Best Practices
- Always create a new object when updating the store (don't mutate the existing one)
- Use the spread operator (
...) to preserve existing properties - Handle nested updates properly by spreading all levels
- Add validation logic inside the update function when appropriate