This repository has been archived on 2024-10-29. You can view files and clone it, but cannot push or open issues or pull requests.
website/tools/authentication/AuthenticationContext.tsx

69 lines
2.1 KiB
TypeScript
Raw Permalink Normal View History

import { createContext, useState, useEffect, useMemo, useContext } from 'react'
2021-10-26 16:38:55 +02:00
import { useTheme } from 'next-themes'
import setLanguage from 'next-translate/setLanguage'
import useTranslation from 'next-translate/useTranslation'
import { Authentication, PagePropsWithAuthentication } from '.'
2021-10-26 16:38:55 +02:00
import { UserCurrent } from '../../models/User'
import { Language, Theme } from '../../models/UserSettings'
export interface AuthenticationValue {
authentication: Authentication
user: UserCurrent
setUser: React.Dispatch<React.SetStateAction<UserCurrent>>
}
const defaultAuthenticationContext: AuthenticationValue = {} as any
const AuthenticationContext = createContext<AuthenticationValue>(
defaultAuthenticationContext
)
export const AuthenticationProvider: React.FC<PagePropsWithAuthentication> = (
props
) => {
const { lang } = useTranslation()
const { theme, setTheme } = useTheme()
const [user, setUser] = useState<UserCurrent>(props.authentication.user)
const authentication = useMemo(() => {
return new Authentication(props.authentication.tokens)
2022-01-13 18:21:45 +01:00
// eslint-disable-next-line react-hooks/exhaustive-deps -- We only want to run this memo once
}, [])
useEffect(() => {
setLanguage(props.authentication.user.settings.language).catch(() => {})
setTheme(props.authentication.user.settings.theme)
// eslint-disable-next-line react-hooks/exhaustive-deps -- We only want to run this effect once
}, [])
useEffect(() => {
authentication.api
.put('/users/current/settings', { theme, language: lang })
.then(() => {
setUser((oldUser) => {
return {
...oldUser,
settings: {
...oldUser.settings,
theme: theme as Theme,
language: lang as Language
}
}
})
})
.catch(() => {})
}, [theme, lang, authentication.api])
return (
<AuthenticationContext.Provider value={{ authentication, user, setUser }}>
{props.children}
</AuthenticationContext.Provider>
)
}
export const useAuthentication = (): AuthenticationValue => {
return useContext(AuthenticationContext)
}