forked from stack-auth/stack-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-platform-persistence.ts
More file actions
47 lines (39 loc) · 1.6 KB
/
use-platform-persistence.ts
File metadata and controls
47 lines (39 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'use client';
import { usePathname } from 'next/navigation';
import { useEffect, useState } from 'react';
import { DEFAULT_PLATFORM, getCurrentPlatform, type Platform } from '../lib/platform-utils';
const STORAGE_KEY = 'stack-docs-platform';
/**
* Hook that manages platform persistence across docs and API navigation.
*
* When user is on docs pages, it detects and stores the current platform.
* When user is on API pages, it returns the stored platform or default.
* This allows seamless navigation back to the correct platform.
*/
export function usePlatformPersistence(): Platform {
const pathname = usePathname();
const [storedPlatform, setStoredPlatform] = useState<Platform>(DEFAULT_PLATFORM);
const [isClient, setIsClient] = useState(false);
// Handle client-side hydration
useEffect(() => {
setIsClient(true);
// Load stored platform from localStorage on client mount
const stored = localStorage.getItem(STORAGE_KEY);
if (stored && ['next', 'react', 'js', 'python'].includes(stored)) {
setStoredPlatform(stored as Platform);
}
}, []);
useEffect(() => {
if (!isClient) return;
// Get current platform from URL (if on docs pages)
const currentPlatform = getCurrentPlatform(pathname);
if (currentPlatform) {
// On docs pages - store the current platform
localStorage.setItem(STORAGE_KEY, currentPlatform);
setStoredPlatform(currentPlatform as Platform);
}
// Note: We don't override stored platform when on non-docs pages
// This preserves the last visited platform for navigation
}, [pathname, isClient]);
return storedPlatform;
}