47 lines
1.1 KiB
TypeScript
47 lines
1.1 KiB
TypeScript
|
|
import { createContext, use, type PropsWithChildren } from 'react'
|
||
|
|
import { useStorageState } from './useStorageState'
|
||
|
|
|
||
|
|
const AuthContext = createContext<{
|
||
|
|
login: () => void
|
||
|
|
logout: () => void
|
||
|
|
session?: string | null
|
||
|
|
isLoading: boolean
|
||
|
|
}>({
|
||
|
|
login: () => null,
|
||
|
|
logout: () => null,
|
||
|
|
session: null,
|
||
|
|
isLoading: false
|
||
|
|
})
|
||
|
|
|
||
|
|
// This hook can be used to access the user info.
|
||
|
|
export function useSession() {
|
||
|
|
const value = use(AuthContext)
|
||
|
|
if (!value) {
|
||
|
|
throw new Error('useSession must be wrapped in a <SessionProvider />')
|
||
|
|
}
|
||
|
|
|
||
|
|
return value
|
||
|
|
}
|
||
|
|
|
||
|
|
export function SessionProvider({ children }: PropsWithChildren) {
|
||
|
|
const [[isLoading, session], setSession] = useStorageState('session')
|
||
|
|
|
||
|
|
return (
|
||
|
|
<AuthContext
|
||
|
|
value={{
|
||
|
|
login: () => {
|
||
|
|
// Perform sign-in logic here
|
||
|
|
setSession('admin')
|
||
|
|
},
|
||
|
|
logout: () => {
|
||
|
|
setSession(null)
|
||
|
|
},
|
||
|
|
session,
|
||
|
|
isLoading
|
||
|
|
}}
|
||
|
|
>
|
||
|
|
{children}
|
||
|
|
</AuthContext>
|
||
|
|
)
|
||
|
|
}
|