All files / src/providers auth.tsx

91.66% Statements 33/36
100% Branches 7/7
100% Functions 2/2
91.66% Lines 33/36

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 701x                 1x     1x                 1x 1x 1x             1x 5x 5x   5x 1x 5x   5x 1x 5x   5x           5x   5x 5x 5x 5x 5x 5x   5x 5x   5x   1x 6x 6x 1x 1x 5x 5x  
import {
  createContext,
  useContext,
  ReactNode,
  useState,
  useCallback,
} from 'react';
 
// Providers
import { useFirebase } from './firebase';
 
// Constants
import { ROUTES } from '@/constants';
 
export type AuthContextType = {
  user: any;
  setUser: (user: any) => void;
  clearUser: () => void;
  signOut: () => Promise<void>;
};
 
export const AuthContext = createContext<AuthContextType | undefined>(
  undefined,
);
 
interface AuthProviderProps {
  initialUser?: any;
  children?: ReactNode;
}
 
export const AuthProvider = ({ initialUser, children }: AuthProviderProps) => {
  const [user, setUserState] = useState(initialUser ?? null);
  const { signOut: signOutFn } = useFirebase();
 
  const setUser = useCallback((newUser: any) => {
    setUserState(newUser);
  }, []);
 
  const clearUser = useCallback(() => {
    setUserState(null);
  }, []);
 
  const signOut = useCallback(async () => {
    await signOutFn(false);
    clearUser();
 
    // Redirect to sign in page to prevent flickering UI
    window.location.replace(ROUTES.SIGN_IN);
  }, [signOutFn, clearUser]);
 
  const contextValue: AuthContextType = {
    user,
    setUser,
    clearUser,
    signOut,
  };
 
  return (
    <AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>
  );
};
 
export const useAuthContext = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuthContext must be used within an AuthProvider');
  }
  return context;
};