Fix WS offline on first login: sync token between api.ts and AuthContext

Two root causes fixed:
1. api.ts saveToken() updated only localStorage, not React state — WS kept
   reconnecting with the expired token. Now dispatches hotelsync:token-updated
   event; AuthContext listens and updates session state, triggering WS reconnect
   with the fresh token.
2. AuthContext mount effect could race with login(): if refresh failed while
   login() was concurrently setting a new token, catch() called setSession(null)
   and wiped the fresh session. Fixed with functional setSession updater that
   checks current state before clearing.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-18 17:37:36 +03:00
parent cbd85c5c7e
commit bc12f8aabc
2 changed files with 34 additions and 7 deletions

View File

@@ -30,6 +30,8 @@ function saveToken(token: string) {
const parsed = JSON.parse(s) as Record<string, unknown>
parsed.token = token
localStorage.setItem('hotelsync-session', JSON.stringify(parsed))
// Notify AuthContext so React state stays in sync (WS reconnects with fresh token)
window.dispatchEvent(new CustomEvent('hotelsync:token-updated', { detail: { token } }))
} catch {
// ignore
}