| import { useState, useEffect } from 'react'; |
| import type { ProjectData } from '@/types/project'; |
| import { DEMO_PROJECTS } from '@/lib/demoData'; |
|
|
| const STORAGE_KEY = 'projectDashboardData'; |
| const TIMESTAMP_KEY = 'projectDashboardLastUpdated'; |
|
|
| |
| |
| |
| |
| export function usePersistence() { |
| const [projects, setProjects] = useState<ProjectData[]>([]); |
| const [lastUpdated, setLastUpdated] = useState<string | null>(null); |
| const [isLoaded, setIsLoaded] = useState(false); |
|
|
| |
| useEffect(() => { |
| loadData(); |
| }, []); |
|
|
| |
| |
| |
| |
| const loadData = () => { |
| try { |
| const savedData = localStorage.getItem(STORAGE_KEY); |
| const savedTimestamp = localStorage.getItem(TIMESTAMP_KEY); |
| |
| if (savedData) { |
| const parsedData = JSON.parse(savedData) as ProjectData[]; |
| setProjects(parsedData); |
| setLastUpdated(savedTimestamp); |
| } else { |
| |
| setProjects(DEMO_PROJECTS); |
| setLastUpdated(null); |
| } |
| } catch (error) { |
| console.error('Failed to load data from localStorage:', error); |
| |
| setProjects(DEMO_PROJECTS); |
| setLastUpdated(null); |
| } finally { |
| setIsLoaded(true); |
| } |
| }; |
|
|
| |
| |
| |
| const saveData = (data: ProjectData[]) => { |
| try { |
| const timestamp = new Date().toISOString(); |
| localStorage.setItem(STORAGE_KEY, JSON.stringify(data)); |
| localStorage.setItem(TIMESTAMP_KEY, timestamp); |
| |
| setProjects(data); |
| setLastUpdated(timestamp); |
| } catch (error) { |
| console.error('Failed to save data to localStorage:', error); |
| throw error; |
| } |
| }; |
|
|
| |
| |
| |
| const clearData = () => { |
| try { |
| localStorage.removeItem(STORAGE_KEY); |
| localStorage.removeItem(TIMESTAMP_KEY); |
| |
| setProjects([]); |
| setLastUpdated(null); |
| } catch (error) { |
| console.error('Failed to clear data from localStorage:', error); |
| throw error; |
| } |
| }; |
|
|
| |
| |
| |
| const getLastUpdatedFormatted = (): string => { |
| if (!lastUpdated) return '暂无数据'; |
| |
| try { |
| const date = new Date(lastUpdated); |
| const year = date.getFullYear(); |
| const month = String(date.getMonth() + 1).padStart(2, '0'); |
| const day = String(date.getDate()).padStart(2, '0'); |
| const hours = String(date.getHours()).padStart(2, '0'); |
| const minutes = String(date.getMinutes()).padStart(2, '0'); |
| |
| return `${year}-${month}-${day} ${hours}:${minutes}`; |
| } catch { |
| return '暂无数据'; |
| } |
| }; |
|
|
| return { |
| projects, |
| lastUpdated, |
| isLoaded, |
| hasData: projects.length > 0, |
| saveData, |
| clearData, |
| getLastUpdatedFormatted, |
| }; |
| } |
|
|