Files
cally/contexts/AuthContext.tsx
2024-08-21 20:03:40 +02:00

81 lines
2.6 KiB
TypeScript

import {createContext, FC, ReactNode, useContext, useEffect, useState} from "react";
import * as SplashScreen from "expo-splash-screen";
import auth, {FirebaseAuthTypes} from "@react-native-firebase/auth";
import {useRouter} from "expo-router";
import firestore from "@react-native-firebase/firestore";
import {UserProfile} from "@/hooks/firebase/types/profileTypes";
type ProfileType = "parent" | "child" | "caregiver" | null;
interface IAuthContext {
user: FirebaseAuthTypes.User | null,
profileType?: ProfileType,
profileData?: UserProfile
setProfileData: (profileData: UserProfile) => void
}
const AuthContext = createContext<IAuthContext>(undefined!)
export const AuthContextProvider: FC<{ children: ReactNode }> = ({children}) => {
const [user, setUser] = useState<FirebaseAuthTypes.User | null>(null)
const [initializing, setInitializing] = useState(true);
const [profileType, setProfileType] = useState<ProfileType | undefined>(undefined);
const [profileData, setProfileData] = useState<UserProfile | undefined>(undefined);
const {replace} = useRouter()
const ready = !initializing
const onAuthStateChanged = async (user: FirebaseAuthTypes.User | null) => {
setUser(user);
if (user) {
try {
const documentSnapshot = await firestore()
.collection("Profiles")
.doc(user.uid)
.get();
if (documentSnapshot.exists) {
setProfileType(documentSnapshot.data()?.profileType);
setProfileData(documentSnapshot.data() as UserProfile)
}
} catch (error) {
console.error("Error fetching user profile type:", error);
setProfileType(null);
}
}
if (initializing) setInitializing(false);
}
useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
return subscriber;
}, []);
useEffect(() => {
if (!initializing) {
SplashScreen.hideAsync();
}
}, [initializing]);
useEffect(() => {
if (ready && user) {
replace({pathname: "/(auth)"})
} else if (ready && !user) {
replace({pathname: "/(unauth)"})
}
}, [user, ready]);
if (!ready) {
return null;
}
return (
<AuthContext.Provider value={{user, profileType, profileData, setProfileData}}>
{children}
</AuthContext.Provider>
)
}
export const useAuthContext = () => useContext(AuthContext)!;