diff --git a/src/components/game/IslandExplorer.client.tsx b/src/components/game/IslandExplorer.client.tsx index 190509544..c45249d23 100644 --- a/src/components/game/IslandExplorer.client.tsx +++ b/src/components/game/IslandExplorer.client.tsx @@ -20,6 +20,7 @@ import { StatsHUD } from './ui/StatsHUD' import { GameMachineProvider } from './machines/GameMachineProvider' import { ProgressionSync } from './machines/ProgressionSync' import { BadgeOverlay } from './ui/BadgeOverlay' +import { useGamePersistence } from './hooks/useGameStore' const LOADING_MESSAGES = [ ['Convincing the waves to behave...', 'They never listen'], @@ -58,6 +59,7 @@ function LoadingOverlay() { export default function IslandExplorer() { const [isLoading, setIsLoading] = useState(true) + useGamePersistence() return ( diff --git a/src/components/game/hooks/useGameStore.ts b/src/components/game/hooks/useGameStore.ts index 51c46232d..4f68e4d55 100644 --- a/src/components/game/hooks/useGameStore.ts +++ b/src/components/game/hooks/useGameStore.ts @@ -1,3 +1,4 @@ +import { useEffect } from 'react' import { create } from 'zustand' import type { IslandData } from '../utils/islandGenerator' import { @@ -997,20 +998,24 @@ export const useGameStore = create()((set, get) => ({ }, })) -// Periodic auto-save and beforeunload handler (client-side only) -if (typeof window !== 'undefined') { - // Auto-save every 5 seconds - setInterval(() => { - const state = useGameStore.getState() - // Only save if game is active - if (state.phase === 'playing' || state.phase === 'gameover') { +export function useGamePersistence() { + useEffect(() => { + const persist = () => { + const state = useGameStore.getState() saveToLocalStorage(extractPersistedState(state)) } - }, 5000) + const interval = window.setInterval(() => { + const state = useGameStore.getState() + if (state.phase === 'playing' || state.phase === 'gameover') { + saveToLocalStorage(extractPersistedState(state)) + } + }, 5000) - // Also save when page is about to unload - window.addEventListener('beforeunload', () => { - const state = useGameStore.getState() - saveToLocalStorage(extractPersistedState(state)) - }) + window.addEventListener('beforeunload', persist) + return () => { + window.clearInterval(interval) + window.removeEventListener('beforeunload', persist) + persist() + } + }, []) }