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:
@@ -1,4 +1,3 @@
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Transaction } from '@/components/TransactionCard';
|
||||
import { useAuth } from '@/contexts/auth/AuthProvider';
|
||||
@@ -23,6 +22,7 @@ import {
|
||||
updateTransactionInSupabase,
|
||||
deleteTransactionFromSupabase
|
||||
} from './supabaseUtils';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
// useTransactions 훅
|
||||
export const useTransactions = () => {
|
||||
@@ -63,10 +63,12 @@ export const useTransactions = () => {
|
||||
toast({
|
||||
title: "데이터 로드 실패",
|
||||
description: "지출 내역을 불러오는데 실패했습니다.",
|
||||
variant: "destructive"
|
||||
variant: "destructive",
|
||||
duration: 4000
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
// 로딩 상태를 약간 지연시켜 UI 업데이트가 원활하게 이루어지도록 함
|
||||
setTimeout(() => setIsLoading(false), 300);
|
||||
}
|
||||
}, []);
|
||||
|
||||
@@ -153,10 +155,14 @@ export const useTransactions = () => {
|
||||
// 이벤트 발생
|
||||
window.dispatchEvent(new Event('transactionUpdated'));
|
||||
|
||||
toast({
|
||||
title: "지출이 수정되었습니다",
|
||||
description: `${updatedTransaction.title} 항목이 업데이트되었습니다.`,
|
||||
});
|
||||
// 약간의 지연을 두고 토스트 표시
|
||||
setTimeout(() => {
|
||||
toast({
|
||||
title: "지출이 수정되었습니다",
|
||||
description: `${updatedTransaction.title} 항목이 업데이트되었습니다.`,
|
||||
duration: 3000
|
||||
});
|
||||
}, 100);
|
||||
};
|
||||
|
||||
// 트랜잭션 삭제
|
||||
@@ -177,10 +183,14 @@ export const useTransactions = () => {
|
||||
// 이벤트 발생
|
||||
window.dispatchEvent(new Event('transactionUpdated'));
|
||||
|
||||
toast({
|
||||
title: "지출이 삭제되었습니다",
|
||||
description: "선택한 지출 항목이 삭제되었습니다.",
|
||||
});
|
||||
// 약간의 지연을 두고 토스트 표시
|
||||
setTimeout(() => {
|
||||
toast({
|
||||
title: "지출이 삭제되었습니다",
|
||||
description: "선택한 지출 항목이 삭제되었습니다.",
|
||||
duration: 3000
|
||||
});
|
||||
}, 100);
|
||||
};
|
||||
|
||||
// 데이터 강제 새로고침
|
||||
|
||||
@@ -1,213 +1,89 @@
|
||||
|
||||
import * as React from "react"
|
||||
import { ToastProps } from "@/components/ui/toast"
|
||||
|
||||
import type {
|
||||
ToastActionElement,
|
||||
ToastProps,
|
||||
} from "@/components/ui/toast"
|
||||
import { useToast as useToastStore } from "@/components/ui/use-toast"
|
||||
import { ToastActionElement } from "@/components/ui/toast"
|
||||
|
||||
// 토스트 알림 표시 제한 및 자동 사라짐 시간(ms) 설정
|
||||
const TOAST_LIMIT = 1
|
||||
const TOAST_REMOVE_DELAY = 3000 // 3초 후 자동으로 사라지도록 설정
|
||||
// 기본 지속 시간 늘리기 (기존 3000ms → 3500ms)
|
||||
export const DEFAULT_TOAST_DURATION = 3500;
|
||||
|
||||
type ToasterToast = ToastProps & {
|
||||
id: string
|
||||
title?: React.ReactNode
|
||||
description?: React.ReactNode
|
||||
action?: ToastActionElement
|
||||
}
|
||||
export const TOAST_REMOVE_DELAY = 1000000;
|
||||
|
||||
const actionTypes = {
|
||||
ADD_TOAST: "ADD_TOAST",
|
||||
UPDATE_TOAST: "UPDATE_TOAST",
|
||||
DISMISS_TOAST: "DISMISS_TOAST",
|
||||
REMOVE_TOAST: "REMOVE_TOAST",
|
||||
} as const
|
||||
export type ToasterToast = ToastProps & {
|
||||
id: string;
|
||||
title?: React.ReactNode;
|
||||
description?: React.ReactNode;
|
||||
action?: React.ReactNode;
|
||||
duration?: number; // 지속 시간 추가
|
||||
};
|
||||
|
||||
const actionTypes = ['default', 'cancel'] as const
|
||||
|
||||
export type ToastActionType = typeof actionTypes[number]
|
||||
|
||||
let count = 0
|
||||
|
||||
function genId() {
|
||||
count = (count + 1) % Number.MAX_SAFE_INTEGER
|
||||
return count.toString()
|
||||
return String(count++)
|
||||
}
|
||||
|
||||
type ActionType = typeof actionTypes
|
||||
export const useToast = () => {
|
||||
const [toasts, setToasts] = React.useState<ToasterToast[]>([]);
|
||||
|
||||
type Action =
|
||||
| {
|
||||
type: ActionType["ADD_TOAST"]
|
||||
toast: ToasterToast
|
||||
}
|
||||
| {
|
||||
type: ActionType["UPDATE_TOAST"]
|
||||
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 addToast = React.useCallback(
|
||||
(props: Omit<ToasterToast, "id">) => {
|
||||
// 토스트에 기본 지속 시간 추가
|
||||
const toastWithDefaults = {
|
||||
...props,
|
||||
duration: props.duration || DEFAULT_TOAST_DURATION,
|
||||
};
|
||||
|
||||
// 이전 토스트 모두 닫기
|
||||
const updatedToasts = state.toasts.map(t => ({
|
||||
...t,
|
||||
open: false
|
||||
}));
|
||||
|
||||
return {
|
||||
...state,
|
||||
toasts: [action.toast, ...updatedToasts].slice(0, TOAST_LIMIT),
|
||||
}
|
||||
const id = genId()
|
||||
|
||||
case "UPDATE_TOAST":
|
||||
return {
|
||||
...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()
|
||||
},
|
||||
setToasts((prev) => [...prev, { id, ...toastWithDefaults }])
|
||||
return id
|
||||
},
|
||||
})
|
||||
[toasts]
|
||||
);
|
||||
|
||||
// 토스트 생성 후 자동으로 3초 후에 사라지도록 설정
|
||||
setTimeout(() => {
|
||||
dismiss()
|
||||
}, TOAST_REMOVE_DELAY)
|
||||
const updateToast = React.useCallback(
|
||||
(id: string, props: Partial<ToasterToast>) => {
|
||||
setToasts((prev) =>
|
||||
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 {
|
||||
id: id,
|
||||
dismiss,
|
||||
update,
|
||||
}
|
||||
}
|
||||
toasts,
|
||||
addToast,
|
||||
updateToast,
|
||||
dismissToast,
|
||||
};
|
||||
};
|
||||
|
||||
function useToast() {
|
||||
const [state, setState] = React.useState<State>(memoryState)
|
||||
|
||||
React.useEffect(() => {
|
||||
listeners.push(setState)
|
||||
return () => {
|
||||
const index = listeners.indexOf(setState)
|
||||
if (index > -1) {
|
||||
listeners.splice(index, 1)
|
||||
}
|
||||
}
|
||||
}, [state])
|
||||
|
||||
return {
|
||||
...state,
|
||||
toast,
|
||||
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
|
||||
}
|
||||
}
|
||||
|
||||
export { useToast, toast }
|
||||
// 전역 토스트 함수에도 기본 지속 시간 적용
|
||||
export const toast = ({
|
||||
...props
|
||||
}: ToastActionElement & {
|
||||
title?: React.ReactNode;
|
||||
description?: React.ReactNode;
|
||||
duration?: number;
|
||||
}) => {
|
||||
// 기본 지속 시간을 적용
|
||||
const toastWithDefaults = {
|
||||
...props,
|
||||
duration: props.duration || DEFAULT_TOAST_DURATION,
|
||||
};
|
||||
|
||||
return toastStore.getState().addToast(toastWithDefaults);
|
||||
};
|
||||
|
||||
@@ -1,5 +1,30 @@
|
||||
|
||||
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 toast = originalToast;
|
||||
export const toast = debouncedToast as typeof originalToast;
|
||||
|
||||
Reference in New Issue
Block a user