feat: multi-tab sync — save on blur, reload from server on focus
Some checks failed
CI/CD — Build & Deploy / Build & Deploy (push) Failing after 19s
Some checks failed
CI/CD — Build & Deploy / Build & Deploy (push) Failing after 19s
- On blur: immediate save to server (no 30s wait) - On focus: fetch server save, load if newer than local - Handles multi-browser scenario (laptop → desktop)
This commit is contained in:
@@ -89,6 +89,36 @@ export function useSaveSync({ getGameState, onLoad, playTimeSeconds }: SaveSyncO
|
||||
return () => clearInterval(interval);
|
||||
}, [saveToServer, user]);
|
||||
|
||||
// Reload from server on tab focus (multi-tab/multi-browser sync)
|
||||
useEffect(() => {
|
||||
if (!user) return undefined;
|
||||
|
||||
const handleFocus = () => {
|
||||
apiRequest("/save").then((data) => {
|
||||
if (data?.gameState && data.lastSave) {
|
||||
// Only load if server save is newer than our last known save
|
||||
if (!lastSaveRef.current || new Date(data.lastSave) > new Date(lastSaveRef.current)) {
|
||||
onLoad(data.gameState);
|
||||
lastSaveRef.current = data.lastSave;
|
||||
console.info("[SaveSync] Reloaded from server on focus");
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleBlur = () => {
|
||||
saveToServer();
|
||||
console.info("[SaveSync] Saved on blur — other tabs will get latest");
|
||||
};
|
||||
|
||||
window.addEventListener("focus", handleFocus);
|
||||
window.addEventListener("blur", handleBlur);
|
||||
return () => {
|
||||
window.removeEventListener("focus", handleFocus);
|
||||
window.removeEventListener("blur", handleBlur);
|
||||
};
|
||||
}, [user, onLoad]);
|
||||
|
||||
// Save on page unload
|
||||
useEffect(() => {
|
||||
const handleUnload = () => {
|
||||
|
||||
Reference in New Issue
Block a user