This repository has been archived on 2024-11-20. You can view files and clone it, but cannot push or open issues or pull requests.
p61-project/presentation/react/contexts/Authentication.tsx

57 lines
1.5 KiB
TypeScript
Raw Permalink Normal View History

import { createContext, useContext, useEffect } from "react"
2024-05-02 23:48:47 +02:00
import { authenticationPresenter } from "@/infrastructure/instances"
import type {
AuthenticationPresenter,
AuthenticationPresenterState,
} from "@/presentation/presenters/Authentication"
2024-05-02 23:48:47 +02:00
import { usePresenterState } from "@/presentation/react/hooks/usePresenterState"
export interface AuthenticationContextValue
extends AuthenticationPresenterState {
authenticationPresenter: AuthenticationPresenter
}
const defaultContextValue = {} as AuthenticationContextValue
const AuthenticationContext =
createContext<AuthenticationContextValue>(defaultContextValue)
interface AuthenticationProviderProps extends React.PropsWithChildren {}
export const AuthenticationProvider: React.FC<AuthenticationProviderProps> = (
props,
) => {
const { children } = props
useEffect(() => {
authenticationPresenter.initialAuthStateListener().catch((error) => {
console.error(error)
})
}, [])
const authenticationPresenterState = usePresenterState(
authenticationPresenter,
)
return (
<AuthenticationContext.Provider
value={{
...authenticationPresenterState,
authenticationPresenter,
}}
>
{children}
</AuthenticationContext.Provider>
)
}
export const useAuthentication = (): AuthenticationContextValue => {
const context = useContext(AuthenticationContext)
if (context === defaultContextValue) {
throw new Error(
"`useAuthentication` must be used within a `AuthenticationProvider`.",
)
}
return context
}