forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseUserLanguage.ts
More file actions
32 lines (27 loc) · 1013 Bytes
/
Copy pathuseUserLanguage.ts
File metadata and controls
32 lines (27 loc) · 1013 Bytes
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
import { useState, useEffect } from 'react'
import Cookies from 'js-cookie'
import { useRouter } from 'next/router'
import { useLanguages } from 'components/context/LanguagesContext'
import { PREFERRED_LOCALE_COOKIE_NAME } from '../../lib/constants.js'
export function useUserLanguage() {
const { locale } = useRouter()
const [userLanguage, setUserLanguage] = useState<string>('en')
const { languages } = useLanguages()
useEffect(() => {
const languagePreferred = [
Cookies.get(PREFERRED_LOCALE_COOKIE_NAME),
navigator.language,
...navigator.languages,
]
.filter(Boolean)
// If it comes from `navigator.language` it most likely will contain
// the region. E.g. `en-US` but in our application, we don't use
// the region.
.map((lang) => lang && lang.slice(0, 2).toLowerCase())
.find((lang) => lang && lang in languages)
if (languagePreferred) {
setUserLanguage(languagePreferred)
}
}, [locale])
return { userLanguage }
}