duration
을 prop으로 받아 Toast별 지속 시간을 다르게 설정할 수 있음.import create from 'zustand';
// Toast 상태 정의
interface ToastState {
toasts: { id: string; message: string; type: 'success' | 'error'; duration: number }[];
addToast: (message: string, type: 'success' | 'error', duration?: number) => void;
removeToast: (id: string) => void;
}
export const useToastStore = create<ToastState>((set) => ({
toasts: [],
addToast: (message, type, duration = 3000) => {
const id = Date.now().toString(); // 고유 ID 생성
set((state) => ({
toasts: [...state.toasts, { id, message, type, duration }],
}));
// duration에 따라 자동 삭제
setTimeout(() => {
set((state) => ({
toasts: state.toasts.filter((toast) => toast.id !== id),
}));
}, duration);
},
removeToast: (id) =>
set((state) => ({
toasts: state.toasts.filter((toast) => toast.id !== id),
})),
}));
tsx
코드 복사
import React from 'react';
import { useToastStore } from './toastStore';
export const ToastContainer = () => {
const toasts = useToastStore((state) => state.toasts);
const removeToast = useToastStore((state) => state.removeToast);
return (
<div className="toast-container">
{toasts.map((toast) => (
<div
key={toast.id}
className={`toast ${toast.type}`}
onClick={() => removeToast(toast.id)}
>
{toast.message}
</div>
))}
</div>
);
};
modalKey
를 활용해 다중 모달을 관리 중.import React, { useState } from 'react';
export const MyModal = () => {
const [isOpen, setIsOpen] = useState(false);
return (
<>
<button onClick={() => setIsOpen(true)}>Open Modal</button>
{isOpen && (
<div className="modal">
<p>This is a modal</p>
<button onClick={() => setIsOpen(false)}>Close Modal</button>
</div>
)}
</>
);
};
이러한 의문점은 계속 가져야하며 프론트엔드의 숙명!!!!!!!! 어떻게 하면 더 효율적일지 계속 생각해가자