import { useState, useEffect } from 'react'; import { v4 as uuidv4 } from 'uuid'; import { Notification } from '@/components/notification/NotificationPopover'; export const useNotifications = () => { const [notifications, setNotifications] = useState([]); // 로컬 스토리지에서 알림 불러오기 useEffect(() => { try { const savedNotifications = localStorage.getItem('notifications'); if (savedNotifications) { const parsedNotifications = JSON.parse(savedNotifications); // 시간 문자열을 Date 객체로 변환 const formattedNotifications = parsedNotifications.map((notification: any) => ({ ...notification, timestamp: new Date(notification.timestamp) })); setNotifications(formattedNotifications); } } catch (error) { console.error('알림 데이터 로드 중 오류 발생:', error); } }, []); // 알림 추가 const addNotification = (title: string, message: string) => { const newNotification: Notification = { id: uuidv4(), title, message, timestamp: new Date(), read: false }; setNotifications(prevNotifications => { const updatedNotifications = [newNotification, ...prevNotifications]; // 로컬 스토리지 업데이트 localStorage.setItem('notifications', JSON.stringify(updatedNotifications)); return updatedNotifications; }); }; // 알림 읽음 표시 const markAsRead = (id: string) => { setNotifications(prevNotifications => { const updatedNotifications = prevNotifications.map(notification => notification.id === id ? { ...notification, read: true } : notification ); // 로컬 스토리지 업데이트 localStorage.setItem('notifications', JSON.stringify(updatedNotifications)); return updatedNotifications; }); }; // 모든 알림 삭제 const clearAllNotifications = () => { setNotifications([]); localStorage.removeItem('notifications'); }; return { notifications, addNotification, markAsRead, clearAllNotifications }; }; export default useNotifications;