Skip to content

Commit 062e3de

Browse files
committed
refactor: implement optimistic updates for chicken inventory and simplify transaction handling
1 parent 665a079 commit 062e3de

File tree

2 files changed

+12
-37
lines changed

2 files changed

+12
-37
lines changed

src/hooks/use-chicken-inventory.ts

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ export function useChickenInventory() {
8484
}
8585

8686
try {
87+
// First fetch the current chicken data to get the correct IDs
8788
const response = await fetch(`${API_BASE_URL}/auth/chickens`, {
8889
headers: { 'Authorization': `Bearer ${user.token}` }
8990
});
@@ -105,6 +106,10 @@ export function useChickenInventory() {
105106

106107
// Only send the update if there's an actual change
107108
if (quantityChange !== 0) {
109+
// Update local state optimistically
110+
setCounts(prev => ({ ...prev, [type]: newQuantity }));
111+
112+
// Send the update to the server with the correct ID
108113
const updateResponse = await fetch(`${API_BASE_URL}/auth/chickens/${chickenToUpdate.id}`, {
109114
method: 'PUT',
110115
headers: {
@@ -115,21 +120,17 @@ export function useChickenInventory() {
115120
});
116121

117122
if (!updateResponse.ok) {
123+
// If update fails, revert the local state
124+
setCounts(prev => ({ ...prev, [type]: currentQuantity }));
118125
throw new Error(`Failed to update chicken inventory: ${updateResponse.status}`);
119126
}
120127
}
121-
122-
// Update local state with the new quantity
123-
setCounts(prev => ({ ...prev, [type]: newQuantity }));
124-
125-
// Refetch the inventory to ensure consistency
126-
await fetchChickenInventory();
127128
} catch (err) {
128129
setError(err instanceof Error ? err.message : 'An unknown error occurred');
129130
} finally {
130131
setLoading(false);
131132
}
132-
}, [user?.token, API_BASE_URL]); // End of updateChickenInventory
133+
}, [user?.token, API_BASE_URL]);
133134

134135
const fetchChickenHistory = useCallback(async (type?: ChickenType, reason?: string) => {
135136
setHistoryLoading(true);

src/pages/Index.tsx

Lines changed: 4 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -239,37 +239,11 @@ const Index = () => {
239239
id: crypto.randomUUID(),
240240
};
241241

242+
// Since the backend already handles chicken inventory updates when posting transactions,
243+
// we only need to fetch the updated data once after the transaction is complete
242244
if (transaction.category === 'chicken') {
243-
const isIncrease = transaction.type === 'expense';
244-
const reason = isIncrease ? 'purchase' : 'sale';
245-
const updatePromises: Promise<void>[] = [];
246-
247-
if (transaction.bulkQuantities) {
248-
const { hen: henCount, cock: cockCount, chicks: chicksCount } = transaction.bulkQuantities;
249-
if (henCount > 0) {
250-
const current = hookChickenCounts.hen;
251-
const newQty = isIncrease ? current + henCount : Math.max(0, current - henCount);
252-
updatePromises.push(hookUpdateChickenInventory('hen' as HookChickenType, newQty, reason));
253-
}
254-
if (cockCount > 0) {
255-
const current = hookChickenCounts.cock;
256-
const newQty = isIncrease ? current + cockCount : Math.max(0, current - cockCount);
257-
updatePromises.push(hookUpdateChickenInventory('cock' as HookChickenType, newQty, reason));
258-
}
259-
if (chicksCount > 0) {
260-
const current = hookChickenCounts.chicks;
261-
const newQty = isIncrease ? current + chicksCount : Math.max(0, current - chicksCount);
262-
updatePromises.push(hookUpdateChickenInventory('chicks' as HookChickenType, newQty, reason));
263-
}
264-
} else if (transaction.chickenType && typeof transaction.quantity === 'number') {
265-
const current = hookChickenCounts[transaction.chickenType as HookChickenType];
266-
const newQty = isIncrease ? current + transaction.quantity : Math.max(0, current - transaction.quantity);
267-
updatePromises.push(hookUpdateChickenInventory(transaction.chickenType as HookChickenType, newQty, reason));
268-
}
269-
270-
// Wait for all chicken inventory updates to complete
271-
// The updateChickenInventory function already refetches the inventory data
272-
await Promise.all(updatePromises);
245+
// Fetch the updated chicken inventory data
246+
await hookFetchChickenInventory();
273247

274248
// Only fetch history if we're on the history tab
275249
if (activeInventoryTab === 'history') {

0 commit comments

Comments
 (0)