1
Fork 0
mirror of https://github.com/Steffo99/festa.git synced 2024-12-22 14:44:21 +00:00

Create a component to provide and store the AuthContext

This commit is contained in:
Steffo 2022-07-17 02:55:36 +02:00
parent 5d633f51bd
commit d5d67dcc6d
Signed by: steffo
GPG key ID: 6965406171929D01
2 changed files with 17 additions and 4 deletions

View file

@ -1,5 +1,7 @@
import { Token, User } from "@prisma/client"
import { default as React } from "react"
import { createStateContext } from "../../utils/stateContext"
import { useLocalStorageAuthState } from "./storage"
/**
@ -16,3 +18,15 @@ export type AuthContextContents = Token & { user: User } | null
* Please note that the data containing in this context is not validated, and has to be validated by the server on every request.
*/
export const AuthContext = createStateContext<AuthContextContents>()
/**
* Component which stores the login status using {@link useLocalStorageAuthState} and provides it to its children through a {@link AuthContext}.
*/
export function AuthContextProvider({ storageKey, children }: { storageKey: string, children: React.ReactNode }) {
return (
<AuthContext.Provider value={useLocalStorageAuthState(storageKey)}>
{children}
</AuthContext.Provider>
)
}

View file

@ -4,7 +4,7 @@ import { AxiosSWRFetcherProvider } from '../components/auth/requests'
import { useStatePostcard } from '../components/postcard/storage'
import { PageErrorBoundary } from '../components/generic/errors/boundaries'
import { PostcardContext } from '../components/postcard/base'
import { AuthContext } from '../components/auth/base'
import { AuthContext, AuthContextProvider } from '../components/auth/base'
import { PostcardRenderer } from '../components/postcard/renderer'
import '../styles/globals.css'
import defaultPostcard from "../public/postcards/adi-goldstein-Hli3R6LKibo-unsplash.jpg"
@ -19,18 +19,17 @@ fontAwesomeConfig.autoAddCss = false
const App = ({ Component, pageProps }: AppProps): JSX.Element => {
const { t } = useTranslation()
const postcardState = useStatePostcard(defaultPostcard)
const authState = useLocalStorageAuthState("auth")
return (
<PageErrorBoundary text={t("genericError")}>
<AxiosSWRFetcherProvider>
<PostcardContext.Provider value={postcardState}>
<AuthContext.Provider value={authState}>
<AuthContextProvider storageKey="auth">
<AxiosSWRFetcherProvider>
<PostcardRenderer />
<Component {...pageProps} />
</AxiosSWRFetcherProvider>
</AuthContext.Provider>
</AuthContextProvider>
</PostcardContext.Provider>
</AxiosSWRFetcherProvider>
</PageErrorBoundary>