Skip to content
This repository was archived by the owner on May 20, 2025. It is now read-only.

Commit b17c04b

Browse files
committed
persist preferred lang across pages and refresh
1 parent e532c80 commit b17c04b

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/hooks/useLang.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ export type LanguageId =
2525

2626
const languages = ['javascript', 'python', 'go', 'typescript', 'dart']
2727

28+
const LOCAL_STORAGE_KEY = 'nitric.docs.selected.language'
29+
2830
const useLang = () => {
2931
const searchParams = useSearchParams()
3032

@@ -52,13 +54,34 @@ const useLang = () => {
5254
const query = search ? `?${search}` : ''
5355

5456
window.history.pushState(null, '', query)
57+
58+
if (query) {
59+
// set language in local storage
60+
try {
61+
localStorage.setItem(LOCAL_STORAGE_KEY, id)
62+
} catch (e) {
63+
// ignore
64+
}
65+
}
5566
},
5667
[searchParams],
5768
)
5869

5970
useEffect(() => {
6071
// add data current lang to body to style based on language, used in hide/show blocks
6172
document.body.dataset.currentLang = currentLanguage
73+
74+
// set query params from local storage if no query params are present
75+
if (!queryParamLang) {
76+
const localLang = localStorage.getItem(LOCAL_STORAGE_KEY) as LanguageId
77+
if (
78+
localLang &&
79+
languages.includes(localLang) &&
80+
localLang !== currentLanguage
81+
) {
82+
setLanguage(localLang)
83+
}
84+
}
6285
}, [currentLanguage])
6386

6487
return {

0 commit comments

Comments
 (0)