import { createContext, Dispatch, SetStateAction, useEffect, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { Auth } from '../services'; import { IAuthState } from '../types'; const InitialAuthState: IAuthState = { valid: false, user: { vatsimId: '', fullName: '', radarScopeKey: '', administrator: false, airportConfigurationAccess: [], }, }; const AuthContext = createContext<{ auth: IAuthState; setAuth: Dispatch>; resetAuth: () => void; }>({ auth: InitialAuthState, setAuth: () => {}, resetAuth: () => {} }); export const AuthProvider = ({ children }: { children: any }) => { const [auth, setAuth] = useState(InitialAuthState); const navigate = useNavigate(); const resetAuth = () => setAuth(InitialAuthState); useEffect(() => { Auth.user().then((user) => { if (user !== undefined) { setAuth({ valid: true, user }); } else { setAuth(InitialAuthState); } }).catch(() => { setAuth(InitialAuthState); navigate('/'); }); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return ( <> {children} ); }; export default AuthContext;