|
|
import { useQuery } from '@tanstack/react-query'; |
|
|
import { createContext, useContext } from 'react'; |
|
|
import { fetchUser } from '../../data/me'; |
|
|
import type { User } from '../../data/types'; |
|
|
|
|
|
export const AUTH_QUERY_KEY = [ 'auth', 'user' ]; |
|
|
|
|
|
interface AuthContextType { |
|
|
user: User; |
|
|
} |
|
|
export const AuthContext = createContext< AuthContextType | undefined >( undefined ); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function AuthProvider( { children }: { children: React.ReactNode } ) { |
|
|
const { |
|
|
data: user, |
|
|
isLoading: userIsLoading, |
|
|
isError: userIsError, |
|
|
} = useQuery( { |
|
|
queryKey: AUTH_QUERY_KEY, |
|
|
queryFn: fetchUser, |
|
|
staleTime: 30 * 60 * 1000, |
|
|
retry: false, |
|
|
meta: { |
|
|
persist: false, |
|
|
}, |
|
|
} ); |
|
|
|
|
|
if ( userIsError ) { |
|
|
if ( typeof window !== 'undefined' ) { |
|
|
const currentPath = window.location.pathname; |
|
|
const loginUrl = `/log-in?redirect_to=${ encodeURIComponent( currentPath ) }`; |
|
|
window.location.href = loginUrl; |
|
|
} |
|
|
return null; |
|
|
} |
|
|
|
|
|
if ( userIsLoading || ! user ) { |
|
|
return null; |
|
|
} |
|
|
|
|
|
return <AuthContext.Provider value={ { user } }>{ children }</AuthContext.Provider>; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function useAuth(): AuthContextType { |
|
|
const context = useContext( AuthContext ); |
|
|
if ( context === undefined ) { |
|
|
throw new Error( 'useAuth must be used within an AuthProvider' ); |
|
|
} |
|
|
return context; |
|
|
} |
|
|
|