Fix toast and data reset issues

- Resolved issue where budget creation toast appeared before expense creation toast.
- Fixed data reset causing a redirect to the login screen.
This commit is contained in:
gpt-engineer-app[bot]
2025-03-16 09:13:08 +00:00
parent 468bb79c9e
commit 7ab79d125e
6 changed files with 213 additions and 240 deletions

View File

@@ -2,7 +2,7 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { PlusIcon } from 'lucide-react'; import { PlusIcon } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from './ui/dialog'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from './ui/dialog';
import { toast } from '@/hooks/use-toast'; import { toast } from '@/hooks/useToast.wrapper';
import { useBudget } from '@/contexts/BudgetContext'; import { useBudget } from '@/contexts/BudgetContext';
import { supabase } from '@/lib/supabase'; import { supabase } from '@/lib/supabase';
import { isSyncEnabled } from '@/utils/syncUtils'; import { isSyncEnabled } from '@/utils/syncUtils';
@@ -11,6 +11,7 @@ import { Transaction } from '@/components/TransactionCard';
const AddTransactionButton = () => { const AddTransactionButton = () => {
const [showExpenseDialog, setShowExpenseDialog] = useState(false); const [showExpenseDialog, setShowExpenseDialog] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const { addTransaction } = useBudget(); const { addTransaction } = useBudget();
// Format number with commas // Format number with commas
@@ -21,7 +22,12 @@ const AddTransactionButton = () => {
}; };
const onSubmit = async (data: ExpenseFormValues) => { const onSubmit = async (data: ExpenseFormValues) => {
// 중복 제출 방지
if (isSubmitting) return;
try { try {
setIsSubmitting(true);
// Remove commas before processing the amount // Remove commas before processing the amount
const numericAmount = data.amount.replace(/,/g, ''); const numericAmount = data.amount.replace(/,/g, '');
@@ -68,11 +74,14 @@ const AddTransactionButton = () => {
// 다이얼로그를 닫습니다 // 다이얼로그를 닫습니다
setShowExpenseDialog(false); setShowExpenseDialog(false);
// 사용자에게 알림을 표시합니다 // 사용자에게 알림을 표시합니다 (지연 추가하여 다른 토스트와 충돌 방지)
toast({ setTimeout(() => {
title: "지출이 추가되었습니다", toast({
description: `${data.title} 항목이 ${formatWithCommas(numericAmount)}원으로 등록되었습니다.`, title: "지출이 추가되었습니다",
}); description: `${data.title} 항목이 ${formatWithCommas(numericAmount)}원으로 등록되었습니다.`,
duration: 3000
});
}, 100);
// 브라우저 이벤트 발생시켜 다른 페이지에서도 업데이트되도록 함 // 브라우저 이벤트 발생시켜 다른 페이지에서도 업데이트되도록 함
window.dispatchEvent(new Event('budgetDataUpdated')); window.dispatchEvent(new Event('budgetDataUpdated'));
@@ -84,7 +93,10 @@ const AddTransactionButton = () => {
title: "지출 추가 실패", title: "지출 추가 실패",
description: "지출을 추가하는 도중 오류가 발생했습니다.", description: "지출을 추가하는 도중 오류가 발생했습니다.",
variant: "destructive", variant: "destructive",
duration: 4000
}); });
} finally {
setIsSubmitting(false);
} }
}; };
@@ -95,19 +107,23 @@ const AddTransactionButton = () => {
className="p-4 rounded-full transition-all duration-300 bg-neuro-income shadow-neuro-flat hover:shadow-neuro-convex text-white animate-pulse-subtle" className="p-4 rounded-full transition-all duration-300 bg-neuro-income shadow-neuro-flat hover:shadow-neuro-convex text-white animate-pulse-subtle"
onClick={() => setShowExpenseDialog(true)} onClick={() => setShowExpenseDialog(true)}
aria-label="지출 추가" aria-label="지출 추가"
disabled={isSubmitting}
> >
<PlusIcon size={24} /> <PlusIcon size={24} />
</button> </button>
</div> </div>
<Dialog open={showExpenseDialog} onOpenChange={setShowExpenseDialog}> <Dialog open={showExpenseDialog} onOpenChange={(open) => {
if (!isSubmitting) setShowExpenseDialog(open);
}}>
<DialogContent className="w-[90%] max-w-sm mx-auto"> <DialogContent className="w-[90%] max-w-sm mx-auto">
<DialogHeader> <DialogHeader>
<DialogTitle> </DialogTitle> <DialogTitle> </DialogTitle>
</DialogHeader> </DialogHeader>
<ExpenseForm <ExpenseForm
onSubmit={onSubmit} onSubmit={onSubmit}
onCancel={() => setShowExpenseDialog(false)} onCancel={() => !isSubmitting && setShowExpenseDialog(false)}
isSubmitting={isSubmitting}
/> />
</DialogContent> </DialogContent>
</Dialog> </Dialog>

View File

@@ -4,6 +4,7 @@ import { useForm } from 'react-hook-form';
import { Form, FormField, FormItem, FormLabel } from '@/components/ui/form'; import { Form, FormField, FormItem, FormLabel } from '@/components/ui/form';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Loader2 } from 'lucide-react';
import ExpenseCategorySelector from './ExpenseCategorySelector'; import ExpenseCategorySelector from './ExpenseCategorySelector';
export interface ExpenseFormValues { export interface ExpenseFormValues {
@@ -15,9 +16,10 @@ export interface ExpenseFormValues {
interface ExpenseFormProps { interface ExpenseFormProps {
onSubmit: (data: ExpenseFormValues) => void; onSubmit: (data: ExpenseFormValues) => void;
onCancel: () => void; onCancel: () => void;
isSubmitting?: boolean;
} }
const ExpenseForm: React.FC<ExpenseFormProps> = ({ onSubmit, onCancel }) => { const ExpenseForm: React.FC<ExpenseFormProps> = ({ onSubmit, onCancel, isSubmitting = false }) => {
const form = useForm<ExpenseFormValues>({ const form = useForm<ExpenseFormValues>({
defaultValues: { defaultValues: {
title: '', title: '',
@@ -47,7 +49,11 @@ const ExpenseForm: React.FC<ExpenseFormProps> = ({ onSubmit, onCancel }) => {
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel></FormLabel> <FormLabel></FormLabel>
<Input placeholder="지출 내역을 입력하세요" {...field} /> <Input
placeholder="지출 내역을 입력하세요"
{...field}
disabled={isSubmitting}
/>
</FormItem> </FormItem>
)} )}
/> />
@@ -62,6 +68,7 @@ const ExpenseForm: React.FC<ExpenseFormProps> = ({ onSubmit, onCancel }) => {
placeholder="금액을 입력하세요" placeholder="금액을 입력하세요"
value={field.value} value={field.value}
onChange={handleAmountChange} onChange={handleAmountChange}
disabled={isSubmitting}
/> />
</FormItem> </FormItem>
)} )}
@@ -75,7 +82,8 @@ const ExpenseForm: React.FC<ExpenseFormProps> = ({ onSubmit, onCancel }) => {
<FormLabel></FormLabel> <FormLabel></FormLabel>
<ExpenseCategorySelector <ExpenseCategorySelector
value={field.value} value={field.value}
onValueChange={(value) => field.onChange(value)} onValueChange={(value) => field.onChange(value)}
disabled={isSubmitting}
/> />
</FormItem> </FormItem>
)} )}
@@ -86,14 +94,21 @@ const ExpenseForm: React.FC<ExpenseFormProps> = ({ onSubmit, onCancel }) => {
type="button" type="button"
variant="outline" variant="outline"
onClick={onCancel} onClick={onCancel}
disabled={isSubmitting}
> >
</Button> </Button>
<Button <Button
type="submit" type="submit"
className="bg-neuro-income text-white hover:bg-neuro-income/90" className="bg-neuro-income text-white hover:bg-neuro-income/90"
disabled={isSubmitting}
> >
{isSubmitting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
...
</>
) : '저장'}
</Button> </Button>
</div> </div>
</form> </form>

View File

@@ -1,7 +1,8 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { Trash2 } from 'lucide-react'; import { Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { useToast } from '@/hooks/use-toast'; import { useToast } from '@/hooks/useToast.wrapper';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { resetAllStorageData } from '@/utils/storageUtils'; import { resetAllStorageData } from '@/utils/storageUtils';
import { import {
@@ -16,20 +17,38 @@ import {
const DataResetSection = () => { const DataResetSection = () => {
const [isResetDialogOpen, setIsResetDialogOpen] = useState(false); const [isResetDialogOpen, setIsResetDialogOpen] = useState(false);
const [isResetting, setIsResetting] = useState(false);
const { toast } = useToast(); const { toast } = useToast();
const navigate = useNavigate(); const navigate = useNavigate();
const handleResetAllData = () => { const handleResetAllData = () => {
// 데이터 초기화 수행 // 데이터 초기화 수행
try { try {
setIsResetting(true);
console.log('모든 데이터 초기화 시작'); console.log('모든 데이터 초기화 시작');
// 초기화 실행 전에 사용자 설정 백업 // 초기화 실행 전에 사용자 설정 백업
const dontShowWelcomeValue = localStorage.getItem('dontShowWelcome'); const dontShowWelcomeValue = localStorage.getItem('dontShowWelcome');
const hasVisitedBefore = localStorage.getItem('hasVisitedBefore'); const hasVisitedBefore = localStorage.getItem('hasVisitedBefore');
// 로그인 관련 설정도 백업
const authSession = localStorage.getItem('authSession'); // 로그인 관련 설정 백업 (supabase 관련 모든 설정)
const sb_auth = localStorage.getItem('sb-auth-token'); const authBackupItems: Record<string, string | null> = {};
// 로그인 관련 항목 수집
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && (
key.includes('supabase') ||
key.includes('auth') ||
key.includes('sb-') ||
key.includes('token') ||
key.includes('user') ||
key.includes('session')
)) {
authBackupItems[key] = localStorage.getItem(key);
console.log(`백업 항목: ${key}`);
}
}
// 데이터 초기화 // 데이터 초기화
resetAllStorageData(); resetAllStorageData();
@@ -44,13 +63,12 @@ const DataResetSection = () => {
} }
// 로그인 관련 설정 복원 (로그인 화면이 나타나지 않도록) // 로그인 관련 설정 복원 (로그인 화면이 나타나지 않도록)
if (authSession) { Object.entries(authBackupItems).forEach(([key, value]) => {
localStorage.setItem('authSession', authSession); if (value) {
} localStorage.setItem(key, value);
console.log(`복원 항목: ${key}`);
if (sb_auth) { }
localStorage.setItem('sb-auth-token', sb_auth); });
}
// 스토리지 이벤트 트리거하여 다른 컴포넌트에 변경 알림 // 스토리지 이벤트 트리거하여 다른 컴포넌트에 변경 알림
window.dispatchEvent(new Event('transactionUpdated')); window.dispatchEvent(new Event('transactionUpdated'));
@@ -58,22 +76,28 @@ const DataResetSection = () => {
window.dispatchEvent(new Event('categoryBudgetsUpdated')); window.dispatchEvent(new Event('categoryBudgetsUpdated'));
window.dispatchEvent(new StorageEvent('storage')); window.dispatchEvent(new StorageEvent('storage'));
toast({ setTimeout(() => {
title: "모든 데이터가 초기화되었습니다.", toast({
description: "모든 예산, 지출 내역, 설정이 초기화되었습니다.", title: "모든 데이터가 초기화되었습니다.",
}); description: "모든 예산, 지출 내역, 설정이 초기화되었습니다.",
setIsResetDialogOpen(false); duration: 3000
console.log('모든 데이터 초기화 완료'); });
setIsResetDialogOpen(false);
// 초기화 후 설정 페이지로 이동 console.log('모든 데이터 초기화 완료');
setTimeout(() => navigate('/settings'), 1000);
// 초기화 후 설정 페이지로 이동
setTimeout(() => navigate('/settings'), 500);
}, 500);
} catch (error) { } catch (error) {
console.error('데이터 초기화 실패:', error); console.error('데이터 초기화 실패:', error);
toast({ toast({
title: "데이터 초기화 실패", title: "데이터 초기화 실패",
description: "데이터를 초기화하는 중 문제가 발생했습니다.", description: "데이터를 초기화하는 중 문제가 발생했습니다.",
variant: "destructive", variant: "destructive",
duration: 4000
}); });
} finally {
setIsResetting(false);
} }
}; };
@@ -93,6 +117,7 @@ const DataResetSection = () => {
variant="destructive" variant="destructive"
className="w-full mt-4" className="w-full mt-4"
onClick={() => setIsResetDialogOpen(true)} onClick={() => setIsResetDialogOpen(true)}
disabled={isResetting}
> >
</Button> </Button>
@@ -110,13 +135,19 @@ const DataResetSection = () => {
</DialogHeader> </DialogHeader>
<DialogFooter className="flex flex-col sm:flex-row gap-2 sm:gap-0"> <DialogFooter className="flex flex-col sm:flex-row gap-2 sm:gap-0">
<DialogClose asChild> <DialogClose asChild>
<Button variant="outline" className="sm:mr-2"></Button> <Button variant="outline" className="sm:mr-2" disabled={isResetting}></Button>
</DialogClose> </DialogClose>
<Button <Button
variant="destructive" variant="destructive"
onClick={handleResetAllData} onClick={handleResetAllData}
disabled={isResetting}
> >
, {isResetting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
...
</>
) : '확인, 모든 데이터 초기화'}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>

View File

@@ -1,4 +1,3 @@
import { useState, useEffect, useCallback } from 'react'; import { useState, useEffect, useCallback } from 'react';
import { Transaction } from '@/components/TransactionCard'; import { Transaction } from '@/components/TransactionCard';
import { useAuth } from '@/contexts/auth/AuthProvider'; import { useAuth } from '@/contexts/auth/AuthProvider';
@@ -23,6 +22,7 @@ import {
updateTransactionInSupabase, updateTransactionInSupabase,
deleteTransactionFromSupabase deleteTransactionFromSupabase
} from './supabaseUtils'; } from './supabaseUtils';
import { Loader2 } from 'lucide-react';
// useTransactions 훅 // useTransactions 훅
export const useTransactions = () => { export const useTransactions = () => {
@@ -63,10 +63,12 @@ export const useTransactions = () => {
toast({ toast({
title: "데이터 로드 실패", title: "데이터 로드 실패",
description: "지출 내역을 불러오는데 실패했습니다.", description: "지출 내역을 불러오는데 실패했습니다.",
variant: "destructive" variant: "destructive",
duration: 4000
}); });
} finally { } finally {
setIsLoading(false); // 로딩 상태를 약간 지연시켜 UI 업데이트가 원활하게 이루어지도록 함
setTimeout(() => setIsLoading(false), 300);
} }
}, []); }, []);
@@ -153,10 +155,14 @@ export const useTransactions = () => {
// 이벤트 발생 // 이벤트 발생
window.dispatchEvent(new Event('transactionUpdated')); window.dispatchEvent(new Event('transactionUpdated'));
toast({ // 약간의 지연을 두고 토스트 표시
title: "지출이 수정되었습니다", setTimeout(() => {
description: `${updatedTransaction.title} 항목이 업데이트되었습니다.`, toast({
}); title: "지출이 수정되었습니다",
description: `${updatedTransaction.title} 항목이 업데이트되었습니다.`,
duration: 3000
});
}, 100);
}; };
// 트랜잭션 삭제 // 트랜잭션 삭제
@@ -177,10 +183,14 @@ export const useTransactions = () => {
// 이벤트 발생 // 이벤트 발생
window.dispatchEvent(new Event('transactionUpdated')); window.dispatchEvent(new Event('transactionUpdated'));
toast({ // 약간의 지연을 두고 토스트 표시
title: "지출이 삭제되었습니다", setTimeout(() => {
description: "선택한 지출 항목이 삭제되었습니다.", toast({
}); title: "지출이 삭제되었습니다",
description: "선택한 지출 항목이 삭제되었습니다.",
duration: 3000
});
}, 100);
}; };
// 데이터 강제 새로고침 // 데이터 강제 새로고침

View File

@@ -1,213 +1,89 @@
import * as React from "react" import * as React from "react"
import { ToastProps } from "@/components/ui/toast"
import type { import { useToast as useToastStore } from "@/components/ui/use-toast"
ToastActionElement, import { ToastActionElement } from "@/components/ui/toast"
ToastProps,
} from "@/components/ui/toast"
// 토스트 알림 표시 제한 및 자동 사라짐 시간(ms) 설정 // 기본 지속 시간 늘리기 (기존 3000ms → 3500ms)
const TOAST_LIMIT = 1 export const DEFAULT_TOAST_DURATION = 3500;
const TOAST_REMOVE_DELAY = 3000 // 3초 후 자동으로 사라지도록 설정
type ToasterToast = ToastProps & { export const TOAST_REMOVE_DELAY = 1000000;
id: string
title?: React.ReactNode
description?: React.ReactNode
action?: ToastActionElement
}
const actionTypes = { export type ToasterToast = ToastProps & {
ADD_TOAST: "ADD_TOAST", id: string;
UPDATE_TOAST: "UPDATE_TOAST", title?: React.ReactNode;
DISMISS_TOAST: "DISMISS_TOAST", description?: React.ReactNode;
REMOVE_TOAST: "REMOVE_TOAST", action?: React.ReactNode;
} as const duration?: number; // 지속 시간 추가
};
const actionTypes = ['default', 'cancel'] as const
export type ToastActionType = typeof actionTypes[number]
let count = 0 let count = 0
function genId() { function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER return String(count++)
return count.toString()
} }
type ActionType = typeof actionTypes export const useToast = () => {
const [toasts, setToasts] = React.useState<ToasterToast[]>([]);
type Action = // 토스트 추가 함수
| { const addToast = React.useCallback(
type: ActionType["ADD_TOAST"] (props: Omit<ToasterToast, "id">) => {
toast: ToasterToast // 토스트에 기본 지속 시간 추가
} const toastWithDefaults = {
| { ...props,
type: ActionType["UPDATE_TOAST"] duration: props.duration || DEFAULT_TOAST_DURATION,
toast: Partial<ToasterToast> };
}
| {
type: ActionType["DISMISS_TOAST"]
toastId?: ToasterToast["id"]
}
| {
type: ActionType["REMOVE_TOAST"]
toastId?: ToasterToast["id"]
}
interface State {
toasts: ToasterToast[]
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId)
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
})
}, TOAST_REMOVE_DELAY)
toastTimeouts.set(toastId, timeout)
}
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
// 동일한 내용의 토스트가 있으면 추가하지 않음
if (state.toasts.some(t =>
t.title === action.toast.title &&
t.description === action.toast.description &&
t.open === true
)) {
return state;
}
// 이전 토스트 모두 닫기 const id = genId()
const updatedToasts = state.toasts.map(t => ({
...t,
open: false
}));
return {
...state,
toasts: [action.toast, ...updatedToasts].slice(0, TOAST_LIMIT),
}
case "UPDATE_TOAST": setToasts((prev) => [...prev, { id, ...toastWithDefaults }])
return { return id
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t
),
}
case "DISMISS_TOAST": {
const { toastId } = action
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId)
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id)
})
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t
),
}
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
}
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
}
}
}
const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }
function dispatch(action: Action) {
memoryState = reducer(memoryState, action)
listeners.forEach((listener) => {
listener(memoryState)
})
}
type Toast = Omit<ToasterToast, "id">
function toast({ ...props }: Toast) {
const id = genId()
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
})
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss()
},
}, },
}) [toasts]
);
// 토스트 생성 후 자동으로 3초 후에 사라지도록 설정 const updateToast = React.useCallback(
setTimeout(() => { (id: string, props: Partial<ToasterToast>) => {
dismiss() setToasts((prev) =>
}, TOAST_REMOVE_DELAY) prev.map((toast) => (toast.id === id ? { ...toast, ...props } : toast))
)
},
[toasts]
)
const dismissToast = React.useCallback(
(id: string) => {
setToasts((prev) => prev.filter((toast) => toast.id !== id))
},
[toasts]
)
return { return {
id: id, toasts,
dismiss, addToast,
update, updateToast,
} dismissToast,
} };
};
function useToast() { // 전역 토스트 함수에도 기본 지속 시간 적용
const [state, setState] = React.useState<State>(memoryState) export const toast = ({
...props
React.useEffect(() => { }: ToastActionElement & {
listeners.push(setState) title?: React.ReactNode;
return () => { description?: React.ReactNode;
const index = listeners.indexOf(setState) duration?: number;
if (index > -1) { }) => {
listeners.splice(index, 1) // 기본 지속 시간을 적용
} const toastWithDefaults = {
} ...props,
}, [state]) duration: props.duration || DEFAULT_TOAST_DURATION,
};
return {
...state, return toastStore.getState().addToast(toastWithDefaults);
toast, };
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
}
}
export { useToast, toast }

View File

@@ -1,5 +1,30 @@
import { useToast as useOriginalToast, toast as originalToast } from '@/hooks/use-toast'; import { useToast as useOriginalToast, toast as originalToast } from '@/hooks/use-toast';
// 토스트 중복 호출 방지를 위한 디바운스 구현
let lastToastTime = 0;
let lastToastMessage = '';
const DEBOUNCE_TIME = 500; // 0.5초 내에 동일 메시지 방지
// 중복 토스트 방지 래퍼 함수
const debouncedToast = (params: Parameters<typeof originalToast>[0]) => {
const now = Date.now();
const currentMessage = params.description?.toString() || '';
// 동일 메시지가 짧은 시간 내에 반복되는 경우 무시
if (now - lastToastTime < DEBOUNCE_TIME && currentMessage === lastToastMessage) {
console.log('중복 토스트 감지로 무시됨:', currentMessage);
return;
}
// 정상적인 토스트 호출
lastToastTime = now;
lastToastMessage = currentMessage;
originalToast({
...params,
duration: params.duration || 3000, // 기본 3초로 설정
});
};
export const useToast = useOriginalToast; export const useToast = useOriginalToast;
export const toast = originalToast; export const toast = debouncedToast as typeof originalToast;