Skip to content

Commit c745779

Browse files
change context to a hook
1 parent fc0e1be commit c745779

File tree

2 files changed

+59
-66
lines changed

2 files changed

+59
-66
lines changed

src/client/App.tsx

Lines changed: 4 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import { fi } from 'date-fns/locale'
88
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFnsV3'
99
import { Box, Button, CssBaseline, Snackbar } from '@mui/material'
1010
import { AppContext } from './contexts/AppContext'
11-
1211
import { PUBLIC_URL } from '../config'
1312
import type { User } from './types'
1413
import useTheme from './theme'
@@ -19,10 +18,10 @@ import { EmbeddedProvider, useIsEmbedded } from './contexts/EmbeddedContext'
1918
import { Feedback } from './components/Feedback'
2019
import { AnalyticsProvider } from './stores/analytics'
2120
import { useTranslation } from 'react-i18next'
21+
import { useUpdateUrlLang } from './hooks/useUpdateUrlLang.tsx'
22+
23+
2224

23-
function useQuery() {
24-
return new URLSearchParams(useLocation().search);
25-
}
2625
const hasAccess = (user: User | null | undefined, courseId?: string) => {
2726
if (!user) return false
2827
if (user.isAdmin) return true
@@ -74,72 +73,13 @@ const AdminLoggedInAsBanner = () => {
7473
/>
7574
)
7675
}
77-
const LanguageContext = createContext({});
78-
79-
export function LanguageProvider({ children }) {
80-
const location = useLocation();
81-
const query = useQuery()
82-
const navigate = useNavigate();
83-
const languages = ['fi', 'sv', 'en']
84-
const { t, i18n } = useTranslation()
85-
const { user, isLoading } = useCurrentUser()
86-
87-
const [lang, setLanguageState] = useState(localStorage.getItem('lang'))
88-
const langParam = query.get('lang')
89-
console.log('language is: ' + lang)
90-
useEffect(() => {
91-
const updatedLangFromLocal = localStorage.getItem('lang')
92-
93-
//use users language as a default if there is no lang url
94-
if (!langParam && !updatedLangFromLocal && user && user.language && languages.includes(user.language)) {
95-
console.log("using default users language")
96-
setLang(user.language)
97-
}
98-
// If there is a lang url, then update the lang state to match it
99-
else if (langParam) {
100-
console.log("lang parameter based update")
101-
setLang(langParam)
102-
}
103-
else if(!langParam && updatedLangFromLocal )
104-
{
105-
console.log("using local storage language")
106-
//there is a case where if there are two redirects after another even the useState gets wiped
107-
// so lets use the local storage (example: see how admin page)
108-
setLang(updatedLangFromLocal)
109-
}
110-
}, [location.pathname])
111-
112-
113-
// sets both the url and the local lang state to match the newlang if the newLang is supported
114-
const setLang= (newLang) => {
115-
if(!languages.includes(newLang)){
116-
console.log("aborted lang update")
117-
return
118-
}
119-
localStorage.setItem('lang', newLang)
120-
setLanguageState(newLang)
121-
i18n.changeLanguage(newLang)
122-
const searchParams = new URLSearchParams(location.search);
123-
searchParams.set('lang', newLang);
124-
navigate(`${location.pathname}?${searchParams.toString()}`, { replace: true });
125-
};
12676

127-
return (
128-
<LanguageContext.Provider value={{ lang, setLang }}>
129-
{children}
130-
</LanguageContext.Provider>
131-
);
132-
}
13377

134-
export function useLanguage() {
135-
return useContext(LanguageContext);
136-
}
13778
const App = () => {
79+
const urlUpdater = useUpdateUrlLang() //DONT REMOVE, the hook creates 2 useEffects to keep the url param synced with user language changes
13880
const theme = useTheme()
13981
const { courseId } = useParams()
14082
const location = useLocation()
141-
const query = useQuery()
142-
const langParam = query.get('lang')
14383
const { user, isLoading } = useCurrentUser()
14484

14585
useEffect(() => {
@@ -157,7 +97,6 @@ const App = () => {
15797
if (!user && !onNoAccessPage) return null
15898

15999
return (
160-
<LanguageProvider>
161100
<ThemeProvider theme={theme}>
162101
<CssBaseline />
163102
<LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fi}>
@@ -170,7 +109,6 @@ const App = () => {
170109
</SnackbarProvider>
171110
</LocalizationProvider>
172111
</ThemeProvider>
173-
</LanguageProvider>
174112
)
175113
}
176114

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import { useTranslation } from "react-i18next";
2+
import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
3+
import useCurrentUser from "../hooks/useCurrentUser";
4+
import { useState, useEffect } from "react";
5+
6+
7+
export const useUpdateUrlLang = () => {
8+
const location = useLocation();
9+
const navigate = useNavigate();
10+
const languages = ['fi', 'sv', 'en']
11+
const { t, i18n } = useTranslation()
12+
const { user, isLoading } = useCurrentUser()
13+
const [lang, setLanguageState] = useState(localStorage.getItem('lang'))
14+
const [params, setParams] = useSearchParams()
15+
const langParam = params.get('lang')
16+
17+
useEffect(() => {
18+
const updatedLangFromLocal = localStorage.getItem('lang')
19+
20+
//use users language as a default if there is no lang url
21+
if (!langParam && !updatedLangFromLocal && user && user.language && languages.includes(user.language)) {
22+
setLang(user.language)
23+
}
24+
// If there is a lang url, then update the lang state to match it
25+
else if (langParam) {
26+
setLang(langParam)
27+
}
28+
else if(!langParam && updatedLangFromLocal )
29+
{
30+
//there is a case where if there are two redirects after another even the useState gets wiped
31+
// so lets use the local storage (example: see how admin page)
32+
setLang(updatedLangFromLocal)
33+
}
34+
}, [location.pathname])
35+
36+
37+
useEffect(() => {
38+
if( i18n.language !== localStorage.getItem('lang')){
39+
localStorage.setItem('lang', i18n.language)
40+
}
41+
}, [i18n.language])
42+
43+
// sets both the url and the local lang state to match the newlang if the newLang is supported
44+
const setLang= (newLang: string) => {
45+
if(!languages.includes(newLang)){
46+
console.log("aborted lang update")
47+
return
48+
}
49+
localStorage.setItem('lang', newLang)
50+
setLanguageState(newLang)
51+
i18n.changeLanguage(newLang)
52+
setParams({lang: newLang})
53+
}
54+
return {}
55+
}

0 commit comments

Comments
 (0)